Android:Parceling对象列表

时间:2013-03-26 15:36:05

标签: android parcelable

我正在为Android应用程序编写代码,如果单击某个列表的元素,它会打开一个新的对象列表,如下所示。

public class A{    
public int id;   
public String name;   
}   

public class B{       
public String name;   
public List<A> a;   
}

如何将B类从一个ListActivity包裹到另一个ListActivity?

这将是我对B的代码: -

public A(Parcel in){

    name = in.readString();     
    in.readList(a, this.getClass().getClassLoader());
}

@Override
public int describeContents() {
    return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {

    dest.writeString(name);
    dest.writeList(a);

}

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

    @Override
    public B[] newArray(int size) {

        return new B[size];
    }

    @Override
    public B createFromParcel(Parcel source) {
        return new B(source);
    }
};

和我的包裹代码A: -

public A(){};

public A(Parcel in){

    id = in.readLong();
    name = in.readString(); 

}

@Override
public int describeContents() {
    return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {

    dest.writeLong(id);
    dest.writeString(name);



}

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

    @Override
    public A[] newArray(int size) {

        return new A[size];
    }

    @Override
    public A createFromParcel(Parcel source) {

        return new A(source);
    }
};

这些不起作用,导致我的应用在尝试打开新列表活动时崩溃。

新的ListActivity代码: -

    private B b; 
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.MainList);
    Bundle bun = getIntent().getExtras();
    b = bun.getParcelable(".modle.B");


    ArrayAdapter<A> adapter =new ArrayAdapter<A>     (this,android.R.layout.simple_list_item_1,b.a);
    setListAdapter(adapter);
}

0 个答案:

没有答案