Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Singleton Class in Android How To Use It?

In Android am trying to understand about what Singleton class is and how to use it. Can it be used like a global variable? That means you can assign data to a Singleton class variable and get it in some other view?

like image 617
MACMAN Avatar asked Mar 26 '18 03:03

MACMAN


1 Answers

To start with, I would like to define what a singleton is. A singleton is a design pattern that restricts the instantation of a class to only one instance. Notable uses include controlling concurrency, and creating a central point of access for an application to access its data store. In android this is very conveinient as many times we need an application to be able to access a central in sync data store from across many differant activities.

Now that we have defined a singleton lets answer your questions followed by a quick example.

  • Can it be used like a global variable?

It is similar to a global variable in the sense that it is accessible from anywhere, however in a certain sense it is restricted and controlled as the instantation is performed by the singleton and not the class that is getting a instance of the singleton. Therefore it allows for a finer grained level of control then a global variable.

  • That means you can assign data to a Singleton class variable and get it in some other view?

Yes, You can use a singleton to store the model data of your application and then provider helper methods that any view in your application will be able to use to get access to the data by obtaining an instance of the object that holds the data through the singleton.

I will now post a simple implementation of a singleton that can be used a central data store.

Here is a very simple singleton that could be used to get access to a List of Customer Objects.

public class CustomerLab {
  private static CustomerLab mCustLab;
  public List<Customer> mCustomers = new ArrayList<Customer>();

  /**
   * The private constructor for the Customer List Singleton class
   */
  private CustomerLab() {}

  public static CustomerLab getCustLab() {
    //instantiate a new CustomerLab if we didn't instantiate one yet
    if (mCustLab == null) {
        mCustLab = new CustomerLab();
    }
    return mCustLab;
  }
  //add methods here for insert, delete, search etc......
}

As you can see, this class has a private constructor and the only way to get an instance is throught the getCustLab() method which uses the pre instantiated object. This allows all parts of an android app to get the same object to access the data store which means that the data will be in a central location and in sync across all sections of your app.

This is the basics of what a singleton class is in android and how to apply it.

like image 81
SteelToe Avatar answered Oct 10 '22 16:10

SteelToe