2015年10月4日 星期日

Send Object to other Activity

Method1(low efficiency)

use Serializable


implement Serializable the class that you want to sent


1
2
3
class Car implements Serializable{}

intent.putExtra("car",car);


Get back the Object from intent


1
Car c2= (Car) intent.getSerializableExtra("car");


Method2

use Parcelable

if i want to send a car object
First, implement Parcelable to car ,and override  some method


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class Car implements Parcelable{

    public Car() {
    }

    protected Car(Parcel in) {
        //what the code here to create the Car from a Parcel
    }

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

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

    @Override
    public int describeContents() {
        return 0;
    }
    
    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString("information");
        dest.writeInt(1);


    }
}

Put into the intent


1
intent.putExtra("key",new Car());

Get back the object


1
intent.getParcelableExtra("key");
parcelable vs serializable