2013년 3월 5일 화요일

Activity 간 객체 넘기기

[객체 클래스]
public class BookData implements Parcelable{
 
 private String title;
    private String author;
 
 public BookData(Parcel in){
  readFromParcel(in);
 }
 
 public BookData(String title, String author) {
  super();
  this.title = title;
  this.author = author;
 }
 
 @Override
 public int describeContents() {
  return 0;
 }

 @Override
 public void writeToParcel(Parcel dest, int flags) {
  dest.writeString(title);
  dest.writeString(author);
 }
 
 public static final Parcelable.Creator CREATOR = new Parcelable.Creator(){
  @Override
  public Object createFromParcel(Parcel source) {
   return new BookData(source);
  }

  @Override
  public Object[] newArray(int size) {
   return new BookData[size];
  }
 };
 
 private void readFromParcel(Parcel in){
  title = in.readString();
        author = in.readString();
 }
 
 public String getTitle() {
  return title;
 }

 public void setTitle(String title) {
  this.title = title;
 }

 public String getAuthor() {
  return author;
 }

 public void setAuthor(String author) {
  this.author = author;
 }
}


public class MainActivity extends Activity {
 Button btn;
 Activity mActivity;
 Context mContext;
 
 BookData data;
 ArrayList array = new ArrayList();
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        mActivity = this;
        mContext = this;
        
        data = new BookData("TITLE1", "TEST1");
        array.add(data);
        
        data = new BookData("TITLE2", "TEST2");
        array.add(data);
        
        
        btn = (Button)findViewById(R.id.button1);
        btn.setOnClickListener(new OnClickListener(){
   @Override
   public void onClick(View v) {
    Intent intent = new Intent(mContext, Test.class);
    intent.putParcelableArrayListExtra("book", array);
    //intent.putExtra("book", data);
    mActivity.startActivity(intent);
    finish();
   }
        });
        
        Log.d("TEST", "onCreate!");
    }
}


public class Test extends Activity{

 BookData book;
 ArrayList arr;
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  
  arr = getIntent().getParcelableArrayListExtra("book");
  
  // Bundle bundle = getIntent().getExtras();
  // book = bundle.getParcelable("book");
  
  for(int i=0; i < arr.size(); i++){
   book = arr.get(i);
   Log.d("TEST", "Author: " + book.getAuthor() + ", Title: " + book.getTitle());
  }
 }
}

댓글 없음:

댓글 쓰기