Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Singleton in Android

I have followed this link and successfully made singleton class in Android. http://www.devahead.com/blog/2011/06/extending-the-android-application-class-and-dealing-with-singleton/

Problem is that i want a single object. like i have Activity A and Activity B. In Activity A I access the object from Singleton class. I use the object and made some changes to it.

When I move to Activity B and access the object from Singleton Class it gave me the initialized object and does not keep the changes which i have made in Activity A. Is there any other way to save the changing? Please help me Experts. This is MainActivity

public class MainActivity extends Activity {     protected MyApplication app;             private OnClickListener btn2=new OnClickListener() {             @Override         public void onClick(View arg0) {             Intent intent=new Intent(MainActivity.this,NextActivity.class);             startActivity(intent);                       }     };     @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);          //Get the application instance         app = (MyApplication)getApplication();          // Call a custom application method         app.customAppMethod();          // Call a custom method in MySingleton         Singleton.getInstance().customSingletonMethod();          Singleton.getInstance();         // Read the value of a variable in MySingleton         String singletonVar = Singleton.customVar;          Log.d("Test",singletonVar);         singletonVar="World";         Log.d("Test",singletonVar);          Button btn=(Button)findViewById(R.id.button1);         btn.setOnClickListener(btn2);     }  } 

This is NextActivity

public class NextActivity extends Activity {          @Override         protected void onCreate(Bundle savedInstanceState) {             super.onCreate(savedInstanceState);             setContentView(R.layout.activity_next);              String singletonVar = Singleton.customVar;              Log.d("Test",singletonVar);         }   } 

Singleton Class

public class Singleton {     private static Singleton instance;      public static String customVar="Hello";      public static void initInstance()     {     if (instance == null)     {       // Create the instance       instance = new Singleton();     }     }      public static Singleton getInstance()     {      // Return the instance      return instance;      }       private Singleton()      {      // Constructor hidden because this is a singleton      }       public void customSingletonMethod()      {      // Custom method      }  } 

and MyApplication

public class MyApplication extends Application     {     @Override     public void onCreate()     {     super.onCreate();       // Initialize the singletons so their instances      // are bound to the application process.      initSingletons();      }       protected void initSingletons()      {      // Initialize the instance of MySingleton      Singleton.initInstance();      }       public void customAppMethod()      {      // Custom application method     } } 

When i run this code, i get Hello which i have initialized in Singleton then World which i gave it in MainActivity and again shows Hello in NextActivity in logcat. I want it to show world again in NextActivity. Please help me to correct this.

like image 337
user2216292 Avatar asked May 13 '13 08:05

user2216292


People also ask

What is singleton used for?

The Singleton's purpose is to control object creation, limiting the number of objects to only one. Since there is only one Singleton instance, any instance fields of a Singleton will occur only once per class, just like static fields.

Is Android service a singleton?

Finally, Service in Android is a singleton. There is only one instance of each service in the system.

What is singleton give example?

Example of singleton classes is Runtime class, Action Servlet, Service Locator. Private constructors and factory methods are also an example of the singleton class.

What is a singleton process?

In software engineering, the singleton pattern is a software design pattern that restricts the instantiation of a class to one "single" instance. This is useful when exactly one object is needed to coordinate actions across the system.


2 Answers

Tip: To create singleton class In Android Studio, right click in your project and open menu:

New -> Java Class -> Choose Singleton from dropdown menu 

enter image description here

like image 109
Lazy Avatar answered Oct 13 '22 21:10

Lazy


EDIT :

The implementation of a Singleton in Android is not "safe" (see here) and you should use a library dedicated to this kind of pattern like Dagger or other DI library to manage the lifecycle and the injection.


Could you post an example from your code ?

Take a look at this gist : https://gist.github.com/Akayh/5566992

it works but it was done very quickly :

MyActivity : set the singleton for the first time + initialize mString attribute ("Hello") in private constructor and show the value ("Hello")

Set new value to mString : "Singleton"

Launch activityB and show the mString value. "Singleton" appears...

like image 30
Akayh Avatar answered Oct 13 '22 20:10

Akayh