1

I need to cache an object to access it every and each Activity and Fragment in my app.

I tried to make it static, But , unfortunately, sometimes Android OS makes this static as null which crashes my app with no reason.

so is it a good practice to use SharedPreferences with Gson to serialize and cache the object on the disk?

Jas
  • 3,207
  • 2
  • 15
  • 45
MBH
  • 16,271
  • 19
  • 99
  • 149

2 Answers2

3

Generaly, you shouldn't use too much the SharedPreferences as it's not as fast as a local database, but actually, you can use it if your set of data is not too big and if you just want a simple cache.

A simple alternative would be to use Realm.

Hugo Gresse
  • 17,195
  • 9
  • 77
  • 119
  • it is single object which contains only 8 variables. but intensively used in every activity..so i was thinking to use SharedPreferences in the beginning of every activity – MBH Oct 06 '15 at 12:36
  • 1
    yes, in `onCreate` or `onResume` load your data from SP and save it in a classic member. Btw, don't use `commit`, use `.apply()` on SP.editor – Hugo Gresse Oct 06 '15 at 12:38
1

sharedPreferences are designed to store data which should be retained between sessions.

If you need that object between the app launches then it's ok to use sharedPreference.

For your problem sharedPreference is a quick solution, however I still encourage you to find reason of your static variable being null.

Rahul Tiwari
  • 6,851
  • 3
  • 49
  • 78
  • 1
    the reason that Android OS is automatically null-ing objects to free some memory. so the problem of null shows up randomely – MBH Oct 06 '15 at 12:38
  • 1
    AFAIK android OS does not do that with static variables. there must be some other reason. how you came to the conclusion that OS is making it null? – Rahul Tiwari Oct 06 '15 at 12:39
  • It happened to me, and I read it here actually: http://stackoverflow.com/a/16736271/2296787 – MBH Oct 06 '15 at 12:42
  • 1
    found something similar [here](http://stackoverflow.com/questions/9541688/static-variable-null-when-returning-to-the-app). still it seems like bad design to store an entire object in shared preference. – Rahul Tiwari Oct 06 '15 at 13:00