Friday, July 29, 2011

Sharing Objects between Activities in Android

It can be difficult and cumbersome sometimes to share arbitrary objects between Activities in Android. For primitives the best way is usually to use SharedPreferences or Intent.putExtra. 
However it is not possible to pass directly an arbitray object to an activity. A simple and effective way is to use static fields on an Application object:


public class MyApplication extends Application {

   public static MyObject myObject;

   @Override
   public void onCreate() {
      super.onCreate();      
      //initialize myObject here, if needed
   }
}


To access myObject from any Activity in the application simply with MyApplication.myObject. This approach allows clear and simple way to exchange data beween Activites.
You could also use a static hashmap, and pass the key around to access the required object.
For interprocess communication more work is required, either a ContentProvider should be used or AIDL, but the purpose of this pattern is to avoid all the boilerplate code associated with it.

1 comment: