tags:

views:

60

answers:

1

Hi, 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?

Thanks in Advance,

+1  A: 

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

Moss
how to access this data in onCreate() method?
Android_programmer_camera
It is the argument which has been provided by onCreate(): public void onCreate(Bundle savedInstanceState)
Moss
how to access myBoolean in onCreate() as it is local variable.If we make it global variable its result will value will not be as same as it is in OnRestoreInstanceState() method
Android_programmer_camera
the idea would be to write the content of 'getBoolean' into a variable taken from the activity. This way you recover that value. I'll edit my post :D
Moss