티스토리 뷰

[안드로이드] Sending data from an Activity to another Activity

 가장 쉬운 방법은 보내고자 하는 Object에 implements java.io.Serializable 하고 ID생성해주고

 Intent intent = new Intent(this , NewActivity.class);
intent.putExtra("ObjectName" , serializedObject);
startActivity(intent);

끝. 

하지만 이건 성능상 약간 느리다고 한다. 약간 더 많은 작업이 필요하지만 성능이 좋은건

Serializable 대신에 Parcelable을 사용하는 것이.




class MyObject implements Parcelable {
   private int data;

  public int describeContents() { return 0; }

  //Parcel에다가 오브젝트에 대한 정보를 쓰는 부분
  public void writeToParcel(Parcel out , int flags) {
    out.writeInt(data);
  }

  //Parcelable로 데이터를 넘겨주려면 CREATOR가 있어야한다. 다음의 두 함수를 구현하면 된다.
  public static final Parcelable.Creator<MyObject> CREATOR = new Parcelable.Creator<MyObject> () {
    public MyObject createFromParcel(Parcel in) {
      return new MyObject(in);
    }
    public MyObject[] newArray(int size) {
      return new MyObject[size];
    }
  } 

  //Parcel을 이용해서 다시 생성하는 부분
  private MyObject(Parcel in) {
    data = in.readInt();
  }



액티비티 간에 보내는건 Serializable하고 같다.

Intent intent = new Intent(this , NewActivity.class);
intent.putExtra("ObjectName" , parcelableObject);
startActivity(intent);

어려운 작업이 아니라면 좀더 속도가 빠른 
Parcelable 쪽을,
그냥 빠르게 구현해야되면 구현이 쉬운 Serializable을 하면 될것이다.

끝. 
 
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/03   »
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
글 보관함