Artem Russakovskii
Artem Russakovskii

Reputation: 22023

Static variables in Android and low memory - a few questions

In my app, I use a static variable to hold the current user id. There is a bug that is very hard to reproduce of this user id simply disappearing. While it could be related to a bug in how this variable is set during application loading (I still wasn't able to reliably reproduce this situation in a controlled environment, so I'm not really sure exactly what happens), I'm starting to think this is related to how memory gets reclaimed from static variables (something I didn't consider before).

So, when can my static variable simply disappear?

Anything adding more clarity to my understanding will be appreciated.

Thank you.

Upvotes: 3

Views: 1273

Answers (2)

Kevin Galligan
Kevin Galligan

Reputation: 17312

This is question super, super old, but I was writing a blog post and mentioned seeing this. I have no idea if you're still working on this app (doubtful), or if you're still seeing this issue (also doubtful). My guess is you set these statics in the Activity that your app launches with. Of course, if your app gets shut down, then restarted, you won't go through that activity.

Lazy loading statics, or initializing them in a custom Application object generally takes care of this.

I've done a fair amount of research on the "statics removed in low memory" idea, and the basic answer is it doesn't happen. Ever.

Upvotes: 1

Kristiono Setyadi
Kristiono Setyadi

Reputation: 5643

I suggest you are not using static variable to hold the current user ID as the static variable is not one of the best way to store your data (I assume userID as a data which will remain on every session of your app, except when the user is logout).

The simplest way is to go with Shared Preferences. Look at the Android Data Storage to read the best (practice) way to store your data in Android.

From your need, I guest you should go on with SharedPreferences. No more problem and you don't even need to simulate any variables reclaimed by the OS.

Upvotes: 0

Related Questions