Tuesday, September 18, 2012

Pass data between Activity-Activity and Activity-Service: Singleton

I managed to pass data between activities and service. Now I knew 2 methods:
  • Intent, Bundle: putting something like int, boolean, ... The tricky is when you try to put some complex data like a class. Implement a class with Parcelable interface will solve the problem. But it's rather complex, I don't know how to talk about it. But if you are interested, check this post (not mine):  Android Parcelable Example.
  • Singleton:  You can take advantage of the fact that your application components run in the same process through the use of a singleton. This is a class that is designed to have only one instance. It has a static method with a name such as getInstance() that returns the instance; the first time this method is called, it creates the global instance. Because all callers get the same instance, they can use this as a point of interaction. For example activity A may retrieve the instance and call setValue(3); later activity B may retrieve the instance and call getValue() to retrieve the last set value.
This post only talks about Singleton.
Because android system may destroy your Singleton instance any time, so it's a Non-Persistent Object. It is suitable for passing data, not for storing data.
This is how to declare it:

public class Singleton {
   private static Singleton instance = null;

   private Int mAnInteger;
   protected Singleton() {
      // Exists only to defeat instantiation.
   }
   public static Singleton getInstance() {
      if(instance == null) {
         instance = new ClassicSingleton();
      }
      return instance;
   }   
   public void setAnInteger(int i) {
      mAnInteger = i;
   }

   public void getAnInteger() {

      return mAnInteger;

   }

}

This is how to use it:
Activity A:
Singleton singleton = Singleton.getInstance();
singleton.setAnInteger(some data here);
Activity B/ Service C:
Singleton singleton = Singleton.getInstance();
int result = singleton.getAnInteger();

You can make pairs of methods get/set with some variables (private). It is very easy to implement (compare to Parcelable interface implementation).
I still don't know what will be its bad side, but it's good for now.

No comments:

Post a Comment