savedInstanceState不为null但没有数据

时间:2016-10-27 03:12:03

标签: java android android-activity

我有一个片段活动,我导航到搜索页面,然后返回到包含结果的列表。有时需要重新创建活动,所以我保存我的实例数据,如下所示:

@Override
public void onSaveInstanceState(Bundle outState) {

    super.onSaveInstanceState(outState);

    System.out.println("Saving instance state!");

    // Save the instance data
    // Filter data
    Intent mIntent = new Intent(this, BasicMapDemoActivity.class);
    filter.addFilterToIntent(mIntent);
    outState = mIntent.getExtras();

    // Save date data
    int year = currentDate.getYear();
    int month = currentDate.getMonth();
    int day = currentDate.getDay();
    outState.putInt("YEAR",year);
    outState.putInt("MONTH",month);
    outState.putInt("DAY",day);

    // Location data
    double latitude = mapLocation.latitude;
    double longitude = mapLocation.longitude;
    outState.putDouble("LATITUDE",latitude);
    outState.putDouble("LONGITUDE",longitude);

    // Other
    outState.putString("VIEW_MODE",viewMode.toString());
    outState.putString("SORT_TYPE",sortType);
    outState.putInt("ZOOM", mapZoom);
}

然后我试图恢复onCreate中的数据,但是当我到达那里时,bundle不是null,但它不包含我保存到它的任何数据。以下所有get函数都返回零(我确认上述代码块末尾的数据为非零):

Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    // If we are 're-creating', then get the old instance data, otherwise set defaults
    if(savedInstanceState == null)
    {
        // Set up default instance data
        currentDate = new Date(115,4,1);
        filter = new ObajoFilter();
        filter.start = currentDate;
        filter.end = new Date(115,4,1,23,59,0);
        viewMode = ViewMode.MAP;
        sortType = "Distance";
        mapLocation = userLocation;
        mapZoom = 16;

    } else {

        // Get date data
        int year = savedInstanceState.getInt("YEAR");
        int month = savedInstanceState.getInt("MONTH");
        int day = savedInstanceState.getInt("DAY");
        currentDate = new Date(year,month,day);

关于什么可以清空捆绑包的任何想法?根据我的理解,只要应用程序被完全销毁,savedInstanceData就会为空。

2 个答案:

答案 0 :(得分:0)

由于此行 outState = mIntent.getExtras();

你的outState指向不同的地址 mIntent.getExtras(),所以它是空的

您应该直接使用outState.putXX而不创建新对象。

答案 1 :(得分:0)

您是否将要保留的信息存储在onSaveInstanceState内容中,如下所示

@Override
public void onSaveInstanceState(Bundle outState) {
    outState.putParcelable("someobject", someobject);
    outState.putBoolean("someboolean", someBoolean);
    outState.putInt("someint", someInt);
    super.onSaveInstanceState(outState);
}