Skip to content Skip to sidebar Skip to footer

How To Pass Reference (non-serializable) From One Activity To Another?

Say I have an reference to an object, how should I go about passing this from one Activity to another? I don't want to have to query the Application Object / singletons / static va

Solution 1:

You can declare a static variable in another activity, or some Global Variable in Application class, then access it to any activity, like you want to parse some Object of Type NewType, to Class NewActivity, from OldActivity. Do as Following:

Declare an Object of Static NewType in NewActivity.java.

publicstatic NewObject newObject=null;

do Following, when you invoke NewActivity.

NewActivity.newObject=item;
Intent intent=newIntent(OldActivity.this, NewActivity.class);
startActivity(intent);

Solution 2:

You can do it in one of the following ways :

  • Make the object Static. (easiest but not always efficient)
  • Serialize -> send -> receive -> deserialize . You can use something like JSON decoding and encoding too, if your class is not serializable. (Involves a lot of over-head, you dont want to use this, unless you have a good reason)
  • Parcelable( Most efficient, Fastest)

Here's an eg from the docs : you can wrap your object with a parcelable, attach it to an intent, and 'un-wrap' it in the recieving activity.

publicclassMyParcelableimplementsParcelable {
     privateint mData;

     publicintdescribeContents() {
         return0;
     }

     publicvoidwriteToParcel(Parcel out, int flags) {
         out.writeInt(mData);
     }

     publicstatic final Parcelable.Creator<MyParcelable> CREATOR
             = new Parcelable.Creator<MyParcelable>() {
         public MyParcelable createFromParcel(Parcel in) {
             returnnew MyParcelable(in);
         }

         public MyParcelable[] newArray(int size) {
             returnnew MyParcelable[size];
         }
     };

     privateMyParcelable(Parcel in) {
         mData = in.readInt();
     }
 }

Solution 3:

One of the Answer :

You can make a singleton class to carry the information you want

for example:

StorageManager.getInstance().saveSomething(Object obj);

then retrieve back with respective getter method

Make sure you take care of the synchronization issues;)

Post a Comment for "How To Pass Reference (non-serializable) From One Activity To Another?"