Reputation: 2369
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
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:
Hope this helps!
Upvotes: 1