Parcelable 인터페이스, Parcelable 오브젝트 사용단계

CODEDRAGON Development/Android

반응형

 

Parcelable 인터페이스

안드로이드에서 자바의 Serialization 개념과 유사한 Parcelable이라는 인터페이스를 제공하고 있습니다.

오브젝트를 Parcelable 클래스로 만들어 주려면 android.os.Parcelable 인터페이스를 구현해야 합니다.

 

 

public interface Parcelable 

https://developer.android.com/reference/android/os/Parcelable.html

 

 

 

Parcelable 오브젝트 사용단계

단계

설명

1

android.os.Parcelable 인터페이스를 구현

2

android.os.Parcelable 인터페이스에 있는 2개의 메소드 오버라이드

3

Parcelable.Creator 타입의 CREATOR라는 변수를 정의

4

모든 parcel된 데이터를 복구하는 생성자를 정의

5

Parcelable 오브젝트를 인텐트로 보내기

6

Parcelable 오브젝트를 가져와서 사용하기

 

 

 

1단계: android.os.Parcelable 인터페이스를 구현

오브젝트를 Parcelable 클래스로 만들어 주려면 android.os.Parcelable 인터페이스를 구현해야 합니다.

public class DataPacel implements Parcelable{

 

    @Override

    public int describeContents() {

        return 0;

    }

 

    @Override

    public void writeToParcel(Parcel dest, int flags) {

    }

}

 

 

 

2단계: android.os.Parcelable 인터페이스에 있는 2개의 메소드 오버라이드

 android.os.Parcelable 인터페이스에 있는 2개의 메소드를 오버라이드 해 줘야만 한다

describeContents()

Parcel 하려는 오브젝트의 종류를 정의한다.

writeToParcel(Parcel dest, int flags)

실제 오브젝트 serialization/flattening을 하는 메소드. 오브젝트의 각 엘리먼트를 각각 parcel해줘야 한다.

 

 

3단계: Parcelable.Creator 타입의 CREATOR라는 변수를 정의

Parcel에서 데이터를 un-marshal/de-serialize하는 단계를 추가해주어야 합니다.

이를 위해 Parcelable.Creator 타입의 CREATOR라는 변수를 정의해야 합니다.

 

public static final Creator<DataPacel> CREATOR = new Creator<DataPacel>() {

 

    @Override

    public DataPacel createFromParcel(Parcel in) {

        return new DataPacel(in);

    }

 

    @Override

    public DataPacel[] newArray(int size) {

        return new DataPacel[size];

    }

};

 

 

 

4단계: 모든 parcel된 데이터를 복구하는 생성자를 정의

모든 parcel된 데이터를 복구하는 생성자를 정의합니다.

이 때 writeToParcel() 메소드에서 기록한 순서와 동일하게 복구해야 합니다(주의).

 

 

5단계: Parcelable 오브젝트를 인텐트로 보내기


putExtra("key", object)

Object인 경우

putParcelableArrayListExtra("key", object)

ArrayList인 경우

 

 

6단계: Parcelable 오브젝트를 가져와서 사용하기


getParcelable("key")

Object인 경우

getParcelableArrayListExtra("key")

ArrayList인 경우

 

 

반응형