Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android : Static variable null on low memory

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?

like image 781
MathieuC Avatar asked Sep 08 '25 18:09

MathieuC


2 Answers

  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.

like image 156
EboMike Avatar answered Sep 10 '25 10:09

EboMike


Most likely the issue is that your application is being killed while it is in the background, and then recreated when you come back to it. Check out the Activity Lifecycle documentation on when this might occur for a single activity. You need to make sure that you move anything stored in memory to more permanent storage at the correct point in time to avoid losing that information if the app gets killed.

I'm not sure what exactly you are storing, but it sounds like using Shared Preferences might work well. This page on Data Storage explains a number of different ways of more permanently storing data, including Shared Preferences.

like image 35
Cheryl Simon Avatar answered Sep 10 '25 08:09

Cheryl Simon