Reputation: 3192
I've noticed, that sometimes (I don't know exactly when and why) system recreates my activities when I send intents to external activities (browser, gallery, camera). Say, my activity has this button:
button.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://google.com");
startActivity(browserIntent);
}
});
I press the button, go to google.com, press back and - my activity is recreated (onCreate is invoked - this is how I detect recreation). In general, this is ok, I heard android can close activities, which are not at the top of stack, when it lacks of memory. But I have a problem connected with this behaviour: when activity is recreated, some of my class fields become null so it causes app crash.
What is the best practice to avoid such crashes?
Upvotes: 1
Views: 425
Reputation: 3966
YOu have told some of your class fields becomes null for that you can use
@Override
protected void onSaveInstanceState(Bundle outState) {
// SAVE YOUR DATA IN OUTSTATE BUNDLE
outState.putBoolean("save value", value);
super.onSaveInstanceState(outState);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
value = savedInstanceState.getBoolean("save value");
super.onRestoreInstanceState(savedInstanceState);
}
onsaveinstancestate will save your values on onpause. onrestoreinstancestate will restore your value when application will resume in this way you can save or restore your values.
one alternative you can also try in your manifest...
android:configChanges="orientation"
but google have not recommended that as it breaks the natural flow of android activities.
Upvotes: 1
Reputation: 7031
Use finish() method as below,
button.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://google.com");
startActivity(browserIntent);
finish();
}
});
Upvotes: 0