2013-08-20 290 views
1

我無法通過Intent傳遞對象。我不斷收到空指針錯誤。這就是:在活動之間傳遞Parcelable項目

在我ListActivity:

@Override 
protected void onListItemClick(ListView l, View v, int position, long id) { 
    Intent intent = new Intent(MyListActivity.this, DetailsActivity.class); 
    intent.putExtra("this_item", my_array.get(position)); 
    startActivity(intent); 
} 

在OnCreate()的DetailsActivity類:

thisItem = (MyObject) getIntent().getExtras().getParcelable("this_item"); 
System.err.println(thisItem.getDescription()); //<--Null pointer error! 

MyObject類並實現Parcelable。爲什麼我不能通過這個對象?我很困惑。謝謝你的幫助。

編輯:這裏是類:

public class MyObject implements Comparable<MyObject>, Parcelable { 

    private Date date; 
    private MyType my_type; 
    private String description; 
    private int flags; 

    public MyObject(Date date, MyType type, String desc) { 
     this.date = date; 
     this.my_type = type; 
     this.description = desc; 
    } 

    public Date getDate() {return date;} 
    public MyType getMyType() {return my_type;} 
    public String getDescription() {return description;} 

    public int compareTo(MyObject another) { 
     if (getDate() == null || another.getDate() == null) {return 0;} 
     return getDate().compareTo(another.getDate()); 
    } 

    public int describeContents() { 
     return 0; 
    } 

    public void writeToParcel(Parcel dest, int flags) { 
     dest.writeInt(flags); 
    } 

    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]; 
     } 
    }; 

    private MyObject (Parcel in) { 
     flags = in.readInt(); 
    } 
} 
+0

你肯定my_array.get(位置)返回一個parcelable對象? –

+1

post MyObject.java – pskink

回答

2

如果你想從一個活動的數據傳遞通過意向另一個actiivty對象必須是你必須實現android..for parcelable parcelable或序列化可序列化interface..for parcelable必須實現parcelable接口..

這樣寫parcelable類.. parcel example

+0

感謝您的鏈接。這對我幫助很大。 – Alex