Android : Static variable null on low memory

MathieuC picture MathieuC · Jan 25, 2011 · Viewed 13.2k times · Source

I have an application which has some static variables. These variables are stored in an independent Class named DataContext. These variables are initialized from raw files at the application start (a method named DataContext.initConstant() is called in the onCreate() of MyApplication which extends Application).

(EDIT : the initConstant method use an AsyncTask to load this data from files).

When my application comes to the background for a certain time or when my application used to much memory, these static variables become null.

  1. How can it be prevented?

  2. If not what should I do with my static variables?

    I have other data which are stored in static variables to be used across different activities, but I clear them or pass them to null in the onLowMemory() of MyApplication.

  3. What is the best way to keep some data accessible between activities if these data are too big to be serialized in an Intent, a database can't be used (for whatever reason), and can't be stored in files through serialization either?

Answer

EboMike picture EboMike · Jan 25, 2011
  1. You can't. Android needs to free up memory from time to time. Imagine if all applications had a ton of static data that is supposed to be resident forever - how would you fit that in memory? It's a mobile phone. It doesn't have virtual memory.

  2. (and 3): Anything that is intended to be persistent needs to be stored, either via SharedPreferences, a Sqlite database, or a file.