Intent to browser causes app to recreate activity

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?

Answers


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.


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();
        }
    });

Need Your Help

Returning a char from a method

java eclipse methods char return

I don't know what's wrong, but I can't get this method to return the characters I'm wanting it to. I just keep getting an error in the form of red lines under the word 'return'