1

我将一些数据存储在 Activity1 的静态变量中,并在 Activity3 和 Activity 5 中访问。即
Activity1---> Activity2--->Activ3
.... ....|
......................Activity4.-----> Activ5

如果我们从 Activity1 完全关闭应用程序,这很好用(即,如果用户在 Activ5 上,如果他点击返回按钮然后 -->Activ4-->Activ2-->Activ1-->Exit)

但是用户通过单击移动退出按钮(不是应用程序退出)在 Activ3、4、5 退出应用程序,现在几小时后用户重新打开应用程序,它(应用程序)从 Activi3 或 4 或 5 启动。(即应用程序关闭的地方)。

现在,由于我正在使用一些数据(我存储在 Activ1 中的静态变量中。)
我得到空值。为什么会这样。如何避免此类错误。
我使用 sharedpref 来避免这种情况。这是唯一的解决方案吗?

4

4 回答 4

1

You need to add onSaveInstanceState methods to your earlier activities, and check the bundle received by the onCreate methods. Check out the Activity Lifecycle for details.

于 2013-11-02T09:59:07.277 回答
1

重新创建活动时恢复活动状态,以便以后可以检索传递的值。例如,对于通过意图传递的整数,请执行以下操作:-

//this will save the value if an activity is killed in background.
@Override
    protected void onSaveInstanceState(Bundle outState) 
    {
        getIntent().putExtra("count", getIntent().getStringExtra("count"));
        super.onSaveInstanceState(outState);
    }

//In restore instance state, retrieve the stored values. The following work can also be done //in oncreate, as when an activity is killed in background, onCreate method is also called.

@Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) 
    {
        if(savedInstanceState == null)
            return;
        int count = getIntent().getIntExtra("count", 0);
        super.onRestoreInstanceState(savedInstanceState);
    }
于 2013-11-02T10:14:59.693 回答
0

您不应该将值存储在静态成员中,活动上下文会被释放,因此您会丢失静态值。在活动之间传递值的首选方式是使用 Bundles 和 Intents。

于 2013-11-02T09:56:36.783 回答
0

您可以创建新类并扩展应用程序,并在其中存储您想要的所有数据,它非常有用,但请记住,如果您这样做,您必须在清单文件中添加应用程序的名称

于 2013-11-02T09:57:53.717 回答