Saving state between actions

I have 2 actions named firstActivity.java, secondActivity.java. When I click the button in firstActivity, I call secondActivity. But when I return from secondActivity, based on the result, I need to skip some of the steps in firstactivity that are executed in its onCreate () method. Returning from secondActivity, I used the Bundle to place the data that I gave as input to the Intent, I accessed this data in onCreate () of the first activity. But while I started working, the application worked, showing as NullPointerException in the line where I access the data of the 2nd action. the reason I think when the application starts for the first time there will be no values ​​in the Bundle, so I get the nullpointer.so exception, can anyone help me sort this problem?

Thanks Advance,

+3
source share
1 answer

You need to implement onSaveInstanceState (Bundle savedInstanceState) and save the values ​​you want to save in the Bundle. Deploy onRestoreInstanceState (Bundle savedInstanceState) to restore the package 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
    }
}

You will find documentation about using state here: http://developer.android.com/reference/android/app/Activity.html

Just search thos methods in docs: P

+8
source

Source: https://habr.com/ru/post/1771473/


All Articles