リア充爆発日記

You don't even know what ria-ju really is.

インテント間でオブジェクトを渡す方法

putExtra()にはプリミティブやString等のI/FはあるけどObjectのI/Fがない。

で、今回ぼくはどうしてもLocation型のオブジェクトが渡したくなったので、どうにか渡せないか調べてみると、ざっくり

の2通りの方法が出てきた。

シリアライズは主にプロセス間での受け渡しにおける安全性や、パフォーマンスに難点があるため、もともとこういう時のために用意されたI/FであるParcelを使うのが好ましいとのこと。
参考:
http://stackoverflow.com/questions/2139134/how-to-send-an-object-from-one-android-activity-to-another-using-intents
http://d.hatena.ne.jp/language_and_engineering/20120313/p1
http://d.hatena.ne.jp/kuwalab/20110207/p1

で、上記のリンクで充分といえば充分なんだけど、実際に動いた実装はこちら。

LocationParcelable.java

public class LocationParcelable implements Parcelable {
    private static final String TAG = LocationParcelable.class.getSimpleName();
    public Location mLocation;

    public LocationParcelable() {

    }
    public LocationParcelable(Location location) {
        this.mLocation = location;
    }

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

    @Override
    public void writeToParcel(Parcel parcel, int i) {
        parcel.writeValue(mLocation);
    }

    public static final Creator<LocationParcelable> CREATOR = new Creator<LocationParcelable>() {
        @Override
        public LocationParcelable createFromParcel(Parcel parcel) {
            final LocationParcelable l = new LocationParcelable();
            l.mLocation = (Location) parcel.readValue(Location.class.getClassLoader());
            return l;
        }

        @Override
        public LocationParcelable[] newArray(int i) {
            return new LocationParcelable[i];
        }
    };
}

Locationオブジェクトを渡す側のActivity

            LocationParcelable parcelable = new LocationParcelable(location);
            intent.putExtra("location", parcelable);

Locationオブジェクト受け取り側のActivity

            LocationParcelable parcelable = (LocationParcelable)intent.getExtras().get("location");
            Location location = parcelable.mLocation;

いやっほい。