Booshan Booshan - 3 months ago 16
Android Question

How to implement singleton pattern in android

I have to use singleton pattern in android. For making better performance it is good to use singleton class. In my application API calls are more, so I have decided to make a common parsing class, which is used for parsing the values. I would like to make it as singleton, so each activity use this class and finally a single instance for this class is created. Please give suggestion on this.

public class parsingclass {
Context context;

public parsingclass(Context context) {
this.context = context;
}

public void parsing methods()
{
//methods for parsing values
}
}


//updated code

public class Singleton {
private static Singleton instance = null;

//a private constructor so no instances can be made outside this class
private Singleton() {}

//Everytime you need an instance, call this
public static Singleton getInstance() {
if(instance == null)
instance = new Singleton();

return instance;
}
public List<String> parsing_home()
{
List<String> set=new ArrayList<String>();
return set;

}

public List<String> parsing_home1()
{
List<String> set=new ArrayList<String>();
return set;

}

//Initialize this or any other variables in probably the Application class
public void init(Context context) {}
}


//call to function

List<String> check=Singleton.getInstance().parsing_home();
List<String> check1=Singleton.getInstance().parsing_home1();

Answer Source

Use this,

public class Singleton {

    private static Singleton instance = null;

    //a private constructor so no instances can be made outside this class
    private Singleton() {}

    //Everytime you need an instance, call this
    //synchronized to make the call thread-safe
    public static synchronized Singleton getInstance() {
        if(instance == null)
          instance = new Singleton();

        return instance;
    }

    //Initialize this or any other variables in probably the Application class
    public void init(Context context) {}

}

EDIT

Made the call to getInstance thread safe by adding synchronized as suggested by @SwederSchellens.