在Activity中传递对象(使用Parcelable方式)

参考文章
Android中如何使用Intent在Activity之间传递对象[使用Serializable或者Parcelable]
[url]http://blog.csdn.net/cjjky/article/details/6441104[/url]

[color=darkred]数据类型有限,比如遇到不可序列化的数据Bitmap,InputStream, 或者LinkList链表等等数据类型就不太好用。
[/color]

要传递的对象

package com.andy.entity;  

package com.andy.entity;

import android.os.Parcel;
import android.os.Parcelable;

public class Police implements Parcelable {

private String name;
private int workTime;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public int getWorkTime() {
return workTime;
}

public void setWorkTime(int workTime) {
this.workTime = workTime;
}

public static final Parcelable.Creator CREATOR = new Creator() {

@Override
public Police createFromParcel(Parcel source) {
Police police = new Police();
police.name = source.readString();
police.workTime = source.readInt();
return police;
}

@Override
public Police[] newArray(int size) {
return new Police[size];
}
};

@Override
public int describeContents() {
return 0;
}

@Override
public void writeToParcel(Parcel parcel, int flags) {
parcel.writeString(name);
parcel.writeInt(workTime);
}
}

/**
* Pacelable传递对象方法
*/
private void PacelableMethod(){
Police mPolice = new Police();
mPolice.setName("I am Police");
mPolice.setWorkTime(2008);
Intent mIntent = new Intent(this,ParcelableDemo.class);
Bundle mBundle = new Bundle();
mBundle.putParcelable(PAR_KEY, mPolice);
mIntent.putExtras(mBundle);

startActivity(mIntent);
}
}



接受对象的Activity

package com.andy.testdemo;

import com.andy.entity.Police;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class ParcelableDemo extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

TextView mTextView = new TextView(this);
Police mPolice = (Police)getIntent().getParcelableExtra(TestActivity.PAR_KEY);
mTextView.setText("Police name is: " + mPolice.getName()+"/n"+
"WorkTime is: " + mPolice.getWorkTime() + "/n");
setContentView(mTextView);
}

}

你可能感兴趣的:(android代码)