0

I need to share a list among all my activities, so I've extended my application class in order to store inside it my list :

public class MyApplication extends Application {
    public ArrayList<Object> theList = new ArrayList<Object>();
}

It works fine, except sometimes when I resume the app, the list is cleared. The list is not null but is empty (while I never clear the list in my code of course).

I wonder why the list is cleared. If it's because of the garbage collector, the list would be null, isn't it ?

Do you know a way to keep data even after resume ?

quent
  • 1,936
  • 1
  • 23
  • 28

1 Answers1

0

Your list lives in RAM, and not on the device storage, so if the app is removed from RAM by the system, even momentarily, the data will be lost.

What you need to do is save the data into a db or shared prefs but also have an in memory model of it as you do.

In MyApplication.onCreate method, start an ASyncTask to load the data from the db or shared prefs, so each time your app is restarted (by the system), it will load the data correctly. Use a boolean in your MyApplication class so you can check if the init is finished, and make it readable from your activities that need the data, so they know if loading data from db is in progress (show loading UI in this case).

Each time you add or remove an item from the list, also carry out the same operation on the db/shared prefs, so your saved data is always in sync with your in memory model.

Whether you choose a db or shared prefs depend on the type of data you have, but as it's a list, I'm guessing a db would make more sense.

FreewheelNat
  • 2,907
  • 1
  • 20
  • 12
  • Thanks for the response. Actually, I don't think my app is killed by the system, Indeed when I resume the app the current activity is the same. – quent Sep 07 '14 at 16:12
  • You could easily verify this by adding a log, in MyApplication onCreate. Also, check the logcat when you run the app (in particular, check for GC messages). However, the important point here is that data that lives only in memory could be lost easily so if you want your data to persist across sessions (even if you just leave the app for 1 second), you should store it on the device. – FreewheelNat Sep 07 '14 at 16:36