티스토리 뷰

Activity간 데이터를 전송하려면 intent를 생성해서 putExtra()메소드로 데이터를 넣어서 startActivity()메소드를 실행하면 되는데. primitive한 자료형만 가능하고 클래스와 같은 데이터는 전송할 수 없다.

따라서 클래스의 내용물을 하나하나 분해해서 putExtra()해야 하지만,

Parcelable인터페이스를 사용하면 깔끔하게 전달할 수 있다.

http://arsviator.blogspot.com/2010/10/parcelable%EC%9D%84-%EC%82%AC%EC%9A%A9%ED%95%9C-%EC%98%A4%EB%B8%8C%EC%A0%9D%ED%8A%B8-%EC%A0%84%EB%8B%AC-object.html

먼저 전달하고자 하는 클래스에 Parcelable 인터페이스를 구현한다.

1 public class Article implements Parcelable{ 2 public int id = -1; 3 public long date = -1; 4 ......

다음으로 Parcelable인터페이스의 두 메소드를 오버라이드한다.

1 @Override 2 public int describeContents() { 3 return 0; 4 } 5 @Override 6 public void writeToParcel(Parcel dest, int flags) { 7 dest.writeInt(id); 8 dest.writeLong(date); 9 ...... 10 }

writeToParcel()은 데이터를 Parcel로 내보내는 과정이고, Parcel을 복구하기 위해서는 다음의 생성자를 추가한다.

1 Article(Parcel src){ 2 this.id = src.readInt(); 3 this.date = src.readLong(); 4 ... 5 }

다음으로 Parcelable.CREATOR를 추가한다.

1 public static final Parcelable.Creator<Article> CREATOR = new Creator<Article>() { 2 @Override 3 public Article createFromParcel(Parcel source) { 4 return new Article(source); 5 } 6 @Override 7 public Article[] newArray(int size) { 8 return new Article[size]; 9 }

이제 클래스를 전달하려면 간단하게 putExtra()를 사용한다.

1 Intent intent = new Intent(TabArticleList.this, TabArticleWrite.class); 2 intent.putExtra("Article", selArticle); 3 startActivity(intent);

클래스를 받는 곳에서는 getExtras()로 받아올 수 있다.

1 Intent intent = getIntent(); 2 Bundle bundle = intent.getExtras(); 3 if (bundle != null){ 4 article = bundle.getParcelable("Article");

 

여러 Activity를 실행하다 보면 Activity를 계속 새로 생성하여 기존 것을 Activity스택에 점점 쌓게 되는데, Back버튼을 누르면 기존의 Activity들이 계속 나타난다. 이 것을 방지하려면 액티비티를 시작할 때FLAG_ACTIVITY_CLEAR_TOP 플래그를 주면 기존의 Activity를 사용하여 스택에 계속 쌓이는 것을 방지할 수 있다.

http://camob.tistory.com/51

EditText가 있는 Activity에서 시작하자마자 바로 키보드가 올라오는 것을 방지하려면,

AndroidManifest.xml에서 해당 activity에

android:windowSoftInputMode="stateHidden”

를 추가해준다.

키보드에 하단의 탭이 같이 올라가는 것을 방지하려면 adjustPan을 같이 추가해준다.

(7/14) Parcel에 byte[]를 넣어서 전달하려는 경우 writeToParcel메소드에서 dest.writeByteArray메소드로 데이터를 집어넣고, 나중에 클래스 생성자에서 src.readByteArray메소드로 복원하게 되는데 무슨 이유인지 계속 readByteArray에서 문제가 발생했다.(널포인트 or array lengths 문제)

public final void readByteArray(byte[] val) { // TODO: make this a native method to avoid the extra copy. byte[] ba = createByteArray(); if (ba.length == val.length) { System.arraycopy(ba, 0, val, 0, ba.length); } else { throw new RuntimeException("bad array lengths"); } }

문제의 readByteArry메소드의 소스인데 val이 null이든, createByteArray메소드를 실행해서 넣어주든 무조건 throw로 빠져 버린다.

해결책은 readByteArray를 사용하지 않고 createByteArray메소드를 사용해야 한다.

byte[] array = src.createByteArray();

Parcel에 rw할때 다른 자료형은 다 read와 write가 짝이 맞는데 왜 byte[]형만 다른지 모르겠다.

몇 시간 동안 씨름하다가 해결했지만 정작 byte[]로 전달하는 것이 효율적이지 않아 사용하지 않았다.

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