jxdwinter
jxdwinter

Reputation: 2369

Android: Activity keep variables in memory

There is an Activity and some variable's. They are passed from previous one. The senerio is :- When users click home button and back to main screen ,after a while users click the application icon to go back to the app , the app crashed. I think that's because Android system killed the activity or something else and then it tries to do the onCreate() , and unfortunatly there is a NullpointerException so the app crashed.

Any idea to fix this or what should I do with this exception? Thanks.

Please allow me to wish you Merry Christmas ahead of the time.

Upvotes: 0

Views: 2134

Answers (1)

Scott Stanchfield
Scott Stanchfield

Reputation: 30634

When you press "home", control goes to the Home application, and the current application is pushed to the background. Android may kill the process at any time to reclaim memory.

When you return to the Activity, it might be the same instance (if Android didn't kill the process) or it might be a new instance of the Activity.

The same thing can happen if memory is very tight and you progress forward from an Activity; the Activity could be released. When you press Back, you may have the same problem.

If you want to keep data, you should use onSaveInstanceState(Bundle) to store any data that you want to recover.

Notice that onCreate() takes a Bundle as an argument. If the Activity was paused (such as happens when you press Home), onSaveInstanceState() is called to allow you to store data temporarily, and that same data is passed back into onCreate(). If the Activity is being launched fresh, that bundle will be null.

So you should do something like:

public void onSaveInstanceState(Bundle bundle) {
    super.onSaveInstanceState(bundle);
    // store data in the bundle
}
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (savedInstanceState != null) {
        // read old data from the Bundle
    } else {
        // you're starting clean; no saved data
    }
    ...
}

A few notes:

  • All data stored in the Bundle must be primitive, Serializable, or better, Parcelable
  • Data in Android's Views that has an android:id set is automatically stored in the bundle and retreived when the Activity is recreated (for example, data typed in an EditText will be saved for you)
  • Other data that is not part of and Android View will not be saved automatically, nor will data in your custom Views

Hope this helps!

Upvotes: 1

Related Questions