Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving state between activities

Tags:

android

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 for the first time there are no values in the Bundle

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

like image 232
Android_programmer_camera Avatar asked Jan 29 '26 06:01

Android_programmer_camera


1 Answers

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

like image 88
Moss Avatar answered Jan 31 '26 21:01

Moss