活动之间保存状态状态

2023-09-05 10:07:04 作者:情场扛把子

我有一个名为firstActivity.java,secondActivity.java 2活动。 当我点击firstActivity一个按钮,我打电话secondActivity。但当我返回从secondActivity的基础上,我需要跳过这是在它的onCreate()方法进行firstactivity一些步骤的结果。 虽然我来自secondActivity我用包把我给作为输入意向数据传回,我访问的第一活动的onCreate()数据。 但是,当我开始活动应用程序崩溃显示为NullPointerException异常在我第二次访问活动的数据线。我想原因是当应用程序启动的第一次也不会有在捆绑让我得到空指针exception.so任何值,任何人都可以帮助我在设法解决这个问题?

I have 2 activities named firstActivity.java,secondActivity.java. When I click a button in firstActivity, I am calling secondActivity .But when I return back from secondActivity ,based on the result I need to skip some steps in firstactivity which are performed in its onCreate() method. While coming back from secondActivity I used Bundle to put data which I gave as input to Intent, I accessed that data in onCreate() of first activity . But while I started activity application was crashing showing as NullPointerException in the line where I am accessing data of 2nd activity. the reason I think is when the application is launched for the first time there will not be any values in Bundle so I am getting nullpointer exception.so, can anyone help me in sorting out this issue?

在此先感谢,

推荐答案

您必须实现的onSaveInstanceState(捆绑savedInstanceState),并节省您想保存到一个捆绑值。实施onRestoreInstanceState(包savedInstanceState)恢复捆绑,并重新设置数据:

You have to implement the onSaveInstanceState(Bundle savedInstanceState) and save the values you would like to save into a Bundle. Implement onRestoreInstanceState(Bundle savedInstanceState) to recover the Bundle and set the data again:

public class MyActivity extends Activity {
    /** The boolean I'll save in a bundle when a state change happens */
    private boolean mMyBoolean;

    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
        savedInstanceState.putBoolean("MyBoolean", mMyBoolean);
        // ... save more data
        super.onSaveInstanceState(savedInstanceState);
    }

    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        mMyBoolean = savedInstanceState.getBoolean("MyBoolean");
        // ... recover more data
    }
}

在这里你可以找到有关国家处理使用文档:http://developer.android.com/reference/android/app/Activity.html

只要搜索的文档茨艾伦方法:P

Just search for thos methods in the docs :P