Do not hold singletons in App level in Android

The first Android project I worked on was a freelance project that I joined midway. That app had singletons in the top App level and used the top level file to store important variables. Since I was completely new to Android development at the time, I thought that holding an instance of the top level App object and using it to “hold” variables as singleton was an acceptable pattern. Oh how wrong I was.

Just to illustrate, this is what I mean by holding variables in top App level and an instance of it.

Here’s your average AndroidManifest.xml

And then

Now, on line 11 – 13, where I hold the instance of App in a static variable and instantiate UserCacher and TokenRefresher and hold the instance of those variables in a static variable?

Yeah… don’t do that. It’s a terrible idea to do so. Here’s a brief explanation from a fellow Android developer who gave me a kind code review that helped me learn a bit more about how Android OS works.

In Android development, we have something called Context. Yeah, that thing that you can get by calling getContext(), getApplicationContext() so that you can call your typical Android system methods on. A context in Android development is like an area in which all instances of objects live in. When that instance of that context dies, all associated components of that context are removed from memory by Android’s garbage collection system. When you hold an instance of the in a static variable like I did in line 11, it means that my ApplicationContext never dies, which eventually leaks memory, causing your app to crash.

Continuing on that front, do not store instances of non-simple objects in a static variable as they are not garbage collected. Stuff like this is fine

This stuff is fine since Strings are simple and won’t add much overhead to matter in your app’s performance. But do not do this with anything else like POJOs, Contexts, Views, and etc as it will cause memory leaks.