我是triyn來實現Parcle數據並通過Intent將它發送給其他類,但獲取NULL對象我是Android新手,如果對不起,那可能會有一些愚蠢的錯誤。按鈕過去了...... Cretaed對象和意圖單擊通過Parcelable傳遞對象,但獲取NULL對象
public class ParceableExampleActivity extends Activity implements View.OnClickListener {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button1 = (Button)findViewById(R.id.button1);
button1.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch(v.getId()){
case R.id.button1:
ParcelData p = new ParcelData();
p.setFirstName("Kumar");
p.setAddedBy(3);
Intent n = new Intent(this,ResultActivity.class);
n.putExtra("data", p);
startActivity(n);
}
}
}
Parceldata它實現pacelclass
public class ParcelData implements Parcelable {
private String firstName ;
private int addedBy ;
//private UUID guid ;
private static final String TAG = "TEST" ;
public ParcelData() {
firstName=null ;
addedBy=0;
// guid=null;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public int getAddedBy() {
return addedBy;
}
public void setAddedBy(int addedBy) {
this.addedBy = addedBy;
}
public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
public Parcelable createFromParcel(Parcel in) {
return new ParcelData();
}
@Override
public Parcelable[] newArray(int size) {
return new Parcelable[size];
}
} ;
public void writeToParcel(Parcel dest, int flags) {
Log.v(TAG, "writeToParcel..."+ flags);
dest.writeString(firstName);
dest.writeInt(addedBy);
}
public void ParcelData(Parcel in){
readFromParcel(in);
}
@Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
private void readFromParcel(Parcel in) {
firstName= in.readString();
addedBy= in.readInt();
}
}
接收對象
public class ResultActivity extends Activity implements View.OnClickListener {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button1 = (Button)findViewById(R.id.button2);
button1.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch(v.getId()){
case R.id.button2:
Bundle b = getIntent().getExtras();
ParcelData result_p=b.getParcelable("data");
Log.v("RESULT", "result of Parcel..."+ result_p.getFirstName());
Log.v("RESULT", "result of Parcel..."+ result_p.getAddedBy());
}
}
}
但日誌的結果是NULL
這是否編譯,無鑄造ParcelData? 'ParcelData result_p = b.getParcelable(「data」);' – Ixx 2012-08-11 18:15:28
@lxx是的,它編譯沒有它 – 2012-08-11 18:18:27
啊,是的,演員是在'getParcelable()'方法,使用泛型完成。 – Ixx 2012-08-11 18:24:27