Android Activity class and static members

In one of my Android application, I was storing some data in a static member variable. After few hours of inactivity, when I used to open the application, I would see that all the data I had stored in the static member variable was gone.

I know about the Android Activity life cycle and that Android can unload Activity class if it is not active. However I did not think that it would reset all static members too. So I had three options to persist data –

  1. Store it in preferences
  2. In a file (local or on external media)
  3. In the database
  4. In the Android application class

See this article for more details about data storage options in Android.  Since the data is not large and I did not already have Android database created for this app  (this app does use database, but it’s HTML5 database), I decided to use option #4. Storing in application class also suited this application because I do not need the data if Android or user kills the application.

So, be very careful when using static variables in Activity class.

-Ram Kulkarni

Social