Q:

A HashMap of Weak References to Objects in android

How do we use a HashMap of Weak References to Objects in android to pass complex objects between activities? I want to pass an object of a class from one activity to another how can I achive this in android. I knew i can use putExtra() method for this. But this methods does not pass any objects directly it pass simple data structures. Please help
Thanks in advance.

A:

I would suggest pass a bundle from one activity to another.
Cretae a class which implements Parceblable interface
public class MyParcel implements Parcelable {
//A HASHMAP WHICH CAN HOLD ALL YOR OBJECTS
private HashMap<String,Object> activityParcel;

public MyParcel(){
    //INITIALIZING A HASHMAP
    activityParcel=new HashMap<String,Object>();

}

public void readFromParcel(Parcel in) {
    int count = in.readInt();
    for (int i = 0; i < count; i++) {
        activityParcel.put(in.readString(), in.readValue(Object.class.getClassLoader()));
    }
}

public MyParcel(Parcel in) {
    activityParcel = new HashMap<String,Object>();
    readFromParcel(in);
}

@Override
public int describeContents() {
    return activityParcel!=null?activityParcel.size():0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {
    dest.writeInt(activityParcel.size());
    for (String s: (Set<String>)activityParcel.keySet()) {
        dest.writeString(s);
        dest.writeValue(activityParcel.get(s));
    }

}
//MANDATORY CLASS MEMBER ,NAME CREATOR IS ALSO MANDATED
public static final Parcelable.Creator<MyParcel> CREATOR=new Parcelable.Creator<MyParcel>() {

    @Override
    public MyParcel createFromParcel(Parcel source) {
        return new MyParcel(source);
    }

    @Override
    public MyParcel[] newArray(int size) {
        return new MyParcel[size];
    }

};

public Object get(String key){
    return activityParcel.get(key);
}

public void put(String key, Object value) {
    activityParcel.put(key, value);
}

}

Now if you want to send your Parcel from Activity A to Activity B
MyParcel myParcel=new MyParcel();
myParcel.put("MyObject", new Date());//sends a blank date object.
Bundle myBundle = new Bundle();
myBundle.putParcelable("My Bundle Key", myParcel);
Intent contentIntent=new Intent(ActivityA.this,ActivityB.class);
startActivity(contentIntent);

now from ActivityB:
Bundle contetnBundle = getIntent().getExtras();

MyParcel myParcel = contetnBundle.getParcelable("My Bundle Key");
Date myDateWithActivityA=(Date)myParcel.get("MyObject");

