Xamarin Android在重新打开应用程序后丢失了数据

时间:2017-02-21 17:13:31

标签: c# android xamarin io xamarin.android

我创建了一个具有保存/加载功能(个人数据等)的应用程序。应用程序运行时,保存和加载数据效果很好。不幸的是,重新打开应用程序后存储的数据消失了,当我尝试打开文件时,我有一个空的引用异常。在设置(tools-> option-> xamarin)中,我选中了“在部署之间保留设备上的应用程序数据/缓存”。以下是我的I / O功能:

public void SerializeObject(T obj)
    {            
        string jsonData = JsonConvert.SerializeObject(obj);
        JsonSerializer serializer = new JsonSerializer();
        serializer.NullValueHandling = NullValueHandling.Ignore;
        var documentsPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
        var filePath = Path.Combine(documentsPath, "data.txt");
        System.IO.File.WriteAllText(filePath, jsonData);
    }
    public T DeSerializeObject()
    {
        var documentsPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
        var filePath = Path.Combine(documentsPath, "data.txt");
        string text = System.IO.File.ReadAllText(filePath);
        T obj = JsonConvert.DeserializeObject<T>(text);
        return obj;
    }

编辑:下面是保存数据的Button.click函数。

 private void saveButtonClick(object sender, EventArgs e)
    {            
        _data.x = this.x;
        _data.y = this.y;
        _data.z = this.z;
        IOoperation<Data> save = new IOoperation<Data>();
        save.SerializeObject(_data);
        TextView _current = FindViewById<TextView>(Resource.Id.currentPositionTextView);
        _current.Text = string.Format("Saved position: {0}, {1}, {2}", _data.x, _data.y, _data.z);
    }

    private void loadButtonClick(object sender, EventArgs e)
    {
        IOoperation<Data> load = new IOoperation<Data>();            
        Data obj = load.DeSerializeObject();

        TextView _current = FindViewById<TextView>(Resource.Id.currentPositionTextView);
        _current.Text = string.Format("Saved position: {0}, {1}, {2} - loaded", _data.x, _data.y, _data.z);
    }

0 个答案:

没有答案