开发者

Saving state between activities

开发者 https://www.devze.com 2023-01-22 05:03 出处:网络
I have 2 activities named FirstActivity.java and SecondActivity.java. When I click a button in FirstActivity, I call SecondActivity. When I return back from SecondActivity, based on the result, I nee

I have 2 activities named FirstActivity.java and SecondActivity.java.

When I click a button in FirstActivity, I call SecondActivity. 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.

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 .

When I start, 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 f开发者_C百科or the first time there are no values in the Bundle

So, can anyone help me in sorting out this issue?


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
    }
}

Here you will find the usage documentation about the state handling: http://developer.android.com/reference/android/app/Activity.html

Just search for thos methods in the docs :P

0

精彩评论

暂无评论...
验证码 换一张
取 消