Xamarin Android:为什么重写OnSaveInstanceState永远不会被调用?

时间:2017-12-20 20:39:05

标签: xamarin xamarin.android

我正在尝试在设备方向更改时保留一些数据,以便不再重新查询SQLite表。这是我的代码:

 SfDataGrid grid;
 string jsonData;

protected override void OnCreate(Bundle savedInstanceState)
{
    base.OnCreate(savedInstanceState);
    SetContentView(Resource.Layout.CaseControl);
    RelativeLayout layout = FindViewById<RelativeLayout>(Resource.Id.layoutCasos);

    grid = new SfDataGrid(this);

    grid.AllowResizingColumn = true;
    grid.AllowSorting = true;

    layout.AddView(grid);

    if (savedInstanceState != null)
    {
       string savedJsonData = savedInstanceState.GetString("jsonData");
       grid.ItemsSource = JsonConvert.DeserializeObject<TableQuery<v_Casos>>(savedJsonData);

    }

    else
    {
        string dpPath = Path.Combine("/data/data/TPProject.TPProject/files/", "PranfHurto.db3");
        var db = new SQLiteConnection(dpPath);
        var data = db.Table<v_Casos>();
        grid.ItemsSource = data;

        jsonData = JsonConvert.SerializeObject(data);
    }

    grid.SelectionMode = SelectionMode.Single;
    grid.GridLongPressed += RowLongPress;

}

protected override void OnSaveInstanceState(Bundle outState)
{
    outState.PutString("jsonData", jsonData);

    base.OnSaveInstanceState(outState);
}

如您所见,我将jsonData放在outState中。但是,在设备方向更改后,它始终返回null。我在该方法中放置了一个断点,但它永远不会被触发。我做错了什么?

1 个答案:

答案 0 :(得分:0)

对我来说,奇怪的解决方案是,不是编写重写方法,而是复制并粘贴它。然后清理并构建解决方案,现在它可以工作。