Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the Android Application Context ever get destroyed?

I use my Android app's application Context as a storage area for "current state" information for my app.

I'm finding that in the field, there are cases when this information goes away on some people's devices causing various NullPointerExceptions since I expect the data to be there when the app resumes and starts rebuilding the necessary activities.

This usually happens when the user hits "Home", does something else, then eventually wanders back into the app - it attempts to go back to where it was before, but the application Context has mysteriously lost all its previously-saved state information (in my case, a few integers and a few Strings).

I know this is a very vague question, but are there any cases (other than the user using "back" to back completely out of the application) where the application Context gets completely destroyed even though the application is not terminated?

Is there a better way to maintain persistent state information?

like image 880
user435210 Avatar asked Nov 09 '10 16:11

user435210


People also ask

Is Android context thread safe?

Context is not threadsafe actually. But it is ok to pass an instance of application context to write to db for example.

What is the application context in Android?

Definition. it's the context of current state of the application/object. It lets newly-created objects understand what has been going on. Typically, you call it to get information regarding another part of your program (activity and package/application).

What is the difference between application context and activity context?

Application Context: It is the application and we are present in Application. For example - MyApplication(which extends Application class). It is an instance of MyApplication only. Activity Context: It is the activity and we are present in Activity.

What is the difference between activity and context?

In android, Context is the main important concept and the wrong usage of it leads to memory leakage. Activity refers to an individual screen and Application refers to the whole app and both extend the Context class.


1 Answers

Yes, it is possible for the Application to be killed and restarted if the user leaves the application for a while. You might want to read this section on processes and lifecycles.

You should find an appropriate place to save state to a persistent store. If its just a few integers and strings, it should be pretty simple to save them to shared preferences as they change. See data storage - shared preferences.

like image 162
Cheryl Simon Avatar answered Sep 29 '22 06:09

Cheryl Simon