3

I've read the documentation for Parcelable, and I could only find read and write functions for primitive data types.

How do you read/write data of Object data type ?

The 'Object' I'm referring to is java.lang.Object

I'm fairly new to Android so all help appreciated.

Traxex1909
  • 2,650
  • 4
  • 20
  • 25

2 Answers2

3

How do you read/write data of Object data type ?

So Parcelable interface is officially recommended way how to pass data via Activities but there is also Serializable interface that provides same solution.

Now maybe many people can disagree with me but i recommend you to use Serializable interface and now you are able in very simple way serialize objects (and also custom objects) through Activities.

All what you need is to use Serializable interface:

public class MyObjectsWrapper implements Serializable {

  private Object obj1;
  private Object obj2;
  private MyCustomObject customObject;

  // getters and setters
}

And an usage:

// inserting data to Intent
Intent i = new Intent(context, Target.class);
i.putExtra("key", myObj);

// retrieving
MyObject obj = getIntent().getSerializableExtra("key");

Reason why i recommend Serializable interface is that is much more simplier for implementing and understanding. Parcelable interface requires much more code to write (it's annoying for me) and in the case you have many objects it takes time to implement it and time is money :)

Simon Dorociak
  • 33,374
  • 10
  • 68
  • 106
  • Thanks for the answer. I'm not sure if i have worded my question properly but i'm using Object data type as a way of storing multiple data types in the same variable, and after retrieving i typecast it to the proper data type that i need. Hope you understand what i mean – Traxex1909 Oct 17 '13 at 10:58
  • The 'Object' I'm referring to is `java.lang.Object`. – Traxex1909 Oct 17 '13 at 11:04
  • @H.Moody If Android API's have provided `parcel` then the use of it must be encouraged. http://stackoverflow.com/a/5551155/1503130 – Prateek Oct 17 '13 at 13:01
-1
public class Teacher implements Parcelable {
String name;
int age;


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

@Override
public void writeToParcel(Parcel dest, int flags) {
    dest.writeString(this.name);
    dest.writeInt(this.age);
}

public Teacher() {
}

protected Teacher(Parcel in) {
    this.name = in.readString();
    this.age = in.readInt();
}

public static final Creator<Teacher> CREATOR = new Creator<Teacher>() {
    @Override
    public Teacher createFromParcel(Parcel source) {
        return new Teacher(source);
    }

    @Override
    public Teacher[] newArray(int size) {
        return new Teacher[size];
    }
};
}
W.Kevin
  • 1
  • 1