What is a singleton on Java/Android?

Cloning - There can only be one

A singleton is simple a class that can be instantiated, but only one instance can exist at a given time in the Java Virtual Machine (Or in Dalvik if you are using Android).

Why is this useful?

In the context of Android, you are the only one running on the JVM. Your phone is not a server where many people connect.

A very specific way this could be useful is when your app is accessing an application object. For your app, there is one application object that can exist. So once one exists in the Dalvik machine, creating a new identical object would be a waste of time and resources.

Picture this, you have a custom Application class, Named MyApplication, that gets user preferences. So you could go about getting the preferences this way:

MyApplication myApplication = new MyApplication();
String userName = myApplication.getUserName();
String password = myApplication.getPassword();

And this code would cause a new MyApplication to be regenerated on every screen and class that needed the preferences. Creating and destroying objects is not an efficient use of resources. Especially when every time you create the MyApplication object, it will look exactly the same.

So that brings us to singletons. Basically, using a little bit of magic (not really), we can make our MyApplication class always return the same instance once an object is created:

public Class MyApplication myApplication{
//1. Create an object of the same type as the class above. This must be static.
private static MyApplication singleton;

//2. Change the empty constructor to private...
private MyApplication{

//3. Create a generator for the class. This will return our class object and essentially replace the constructor.
public getMyApplication(){
if (singleton == null){
singleton= new MyApplication(); //This only executes if singleton does not exist
return singleton;

Then to instantiate the MyApplication object, you simply call the generator instead of a constructor:

MyApplication myApplication = MyApplication.getMyApplication();
String userName = myApplication.getUserName();
String password = myApplication.getPassword();

By operating in this fashion, only one instance is ever created, potentially saving cpu cycles and memory.  There are many uses of singletons, but this is just one very specific and practical use in Android.

The end result is a more efficient and more responsive app for your Android users! Happy coding!

Leave a Reply