A singleton in android it’s the same that in Java. A singleton is a class for which only one instance can be created provides a global point of access this instance. The singleton pattern describe how this can be archived.
Singletons are useful to provide a unique source of data or functionality to other Java Objects. For example you may use a singleton to access your data model from within your application or to define logger which the rest of the application can use.
public class Singleton {
private static Singleton mInstance = null;
private String mString;
private Singleton(){
mString = "Hello";
}
public static Singleton getInstance(){
if(mInstance == null)
{
mInstance = new Singleton();
}
return mInstance;
}
public String getString(){
return this.mString;
}
public void setString(String value){
mString = value;
}
}
In ActivityA We set the string value.
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;
public class ActivityA extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//Show the string value defined by the private constructor
Toast.makeText(getApplicationContext(),Singleton.getInstance().getString(), Toast.LENGTH_LONG).show();
//Change the string value and launch intent to ActivityB
Singleton.getInstance().setString("Singleton");
Intent intent = new Intent(getApplicationContext(),ActivityB.class);
this.startActivity(intent);
}
}
In ActivityB We get the string.
import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;
public class ActivityB extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Show the string value of the singleton
Toast.makeText(getApplicationContext(),Singleton.getInstance().getString(), Toast.LENGTH_SHORT).show();
}
}
Very good tutorial Thanks