티스토리 뷰

반응형

Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.

Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.

 

아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.

How to send an object from one Android Activity to another using Intents?

intent를 사용하여 다른 액티비티로 object를 보내는 방법

 문제 내용 

How can I pass an object of a custom type from one Activity to another using the putExtra() method of the class Intent?

Intent의 putExtra() 메서드를 사용하여 사용자 지정 유형의 오브젝트를 한 액티비티에서 다른 액티비티로 전달하려면 어떻게 해야 합니까?

 

 

 

 높은 점수를 받은 Solution 

If you're just passing objects around then Parcelable was designed for this. It requires a little more effort to use than using Java's native serialization, but it's way faster (and I mean way, WAY faster).

객체를 그냥 전달하는 경우 이를 위해 Parcelable이 설계되었습니다. Java의 기본 직렬화를 사용하는 것보다 사용하는 데 약간의 노력이 더 필요하지만 훨씬 더 빠릅니다.

 

From the docs, a simple example for how to implement is:

문서에서 구현 방법에 대한 간단한 예는 다음과 같습니다.
// simple class that just has one member property as an example
public class MyParcelable implements Parcelable {
    private int mData;

    /* everything below here is for implementing Parcelable */

    // 99.9% of the time you can just ignore this
    @Override
    public int describeContents() {
        return 0;
    }

    // write your object's data to the passed-in Parcel
    @Override
    public void writeToParcel(Parcel out, int flags) {
        out.writeInt(mData);
    }

    // this is used to regenerate your object. All Parcelables must have a CREATOR that implements these two methods
    public static final Parcelable.Creator<MyParcelable> CREATOR = new Parcelable.Creator<MyParcelable>() {
        public MyParcelable createFromParcel(Parcel in) {
            return new MyParcelable(in);
        }

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

    // example constructor that takes a Parcel and gives you an object populated with it's values
    private MyParcelable(Parcel in) {
        mData = in.readInt();
    }
}

 

Observe that in the case you have more than one field to retrieve from a given Parcel, you must do this in the same order you put them in (that is, in a FIFO approach).

지정된 Parcel에서 검색할 필드가 둘 이상인 경우 필드를 넣은 순서대로(즉, FIFO 접근 방식에서) 이 작업을 수행해야 합니다.

 

Once you have your objects implement Parcelable it's just a matter of putting them into your Intents with putExtra():

개체가 Parcelable을 구현하게 되면 putExtra()를 사용하여 object를 인텐트에 넣기만 하면 됩니다.

 

Intent i = new Intent();
i.putExtra("name_of_extra", myParcelableObject);

Then you can pull them back out with getParcelableExtra():

그런 다음 getParcelableExtra()로 다시 끌어낼 수 있습니다.:
Intent i = getIntent();
MyParcelable myParcelableObject = (MyParcelable) i.getParcelableExtra("name_of_extra");

 

If your Object Class implements Parcelable and Serializable then make sure you do cast to one of the following:

객체 클래스가 Parcelable 및 Serializable을 구현하는 경우 다음 중 하나로 캐스트해야 합니다.
i.putExtra("parcelable_extra", (Parcelable) myParcelableObject);
i.putExtra("serializable_extra", (Serializable) myParcelableObject);

 

 

 가장 최근 달린 Solution 

Easiest and java way of doing is : implement serializable in your pojo/model class

가장 쉽고 자바한 방법 : pojo/모델 클래스에서 직렬화 가능한 기능을 구현하는 것입니다.

 

Recommended for Android for performance view: make model parcelable

성능 보기를 위해 Android용으로 권장: 모델을 포장 가능하게 만들기

 

 

 

출처 : https://stackoverflow.com/questions/2139134/how-to-send-an-object-from-one-android-activity-to-another-using-intents

반응형
댓글
공지사항
최근에 올라온 글