Daniel Ortiz
Daniel Ortiz

Reputation: 21

Android: How to send an objects with member objects through bundle?

I have found a few simple examples of how to do this with an object that contains primitive types. I am working with a class that contains an array of objects as one of its members and several enumeration member variables. How would I store each object? I assume I would have to make both implement Parcelable. Are there any examples out there or others who have dealt with this problem?

How to send objects through bundle

Upvotes: 0

Views: 188

Answers (2)

Benoit
Benoit

Reputation: 4599

The Parcel interface gives you different possibilities for your array of objects

writeParcelableArray(T[] value, int parcelableFlags)
writeStringArray(String[] val)
writeStringList(List<String> val)

readParcelableArray(ClassLoader loader)
readStringList(List<String> list)
readStringArray(String[] val)

And for the Enum's you can either save the name and recreate it later using

readString()
writeString(String val)

Or getting the enum value and using

readInt()
writeInt(Int val)

Small code sample

public class Tag implements Parcelable {

private long id;
private String title;

// ... getter & setters & constructor ...

@Override
public int describeContents() {
    return 0;
}

@Override
public void writeToParcel(Parcel out, int flags) {
    out.writeLong(id);
    out.writeString(title);
}

public static final transient Parcelable.Creator<Tag> CREATOR = new Parcelable.Creator<Tag>() {
    public Tag createFromParcel(Parcel in) {
        return new Tag(in);
    }

    public Tag[] newArray(int size) {
        return new Tag[size];
    }
};

protected Tag(Parcel in) {
    readFromParcel(in);
}

protected final void readFromParcel(Parcel in) {
    id = in.readLong();
    title = in.readString();
}
}

Upvotes: 1

Vishal Mokal
Vishal Mokal

Reputation: 800

i hope JSONObject will help you in this . you can put other object in to one json object by using put method ... and you can send that object by writing it in to any .txt or .json file and you can just parse that file and get all those object that you have write in to file

Upvotes: 1

Related Questions