在活动之间传递ArrayList<CustomObject>

4
我已经实现了一个Parcelable类:
public class Evento implements Parcelable {
    private int;
    private String ;
    private String imagen;
    //more atts

    //Constructors, setters and getters

public Evento(Parcel in) {
    this.id = in.readInt();
    this.titulo = in.readString();
    this.imagen=in.readString();

public void writeToParcel(Parcel dest, int flags) {     
    dest.writeInt(id);
    dest.writeString(titulo);
    dest.writeString(imagen);       
}
public static final Parcelable.Creator<Evento> CREATOR = new Parcelable.Creator<Evento>() {
    @Override
    public Evento createFromParcel(Parcel in) {
        return new Evento(in);
    }

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

在我的活动中,我尝试将一个ArrayList传递给另一个活动: 我重写了onItemClick并通过以下方式传递信息:

public void onItemClick(AdapterView<?> a, View v, int position, long id) {
            //create new activitie
            ArrayList<Eventos> eventos = new ArrayList<Eventos>();
            Intent intent = new Intent(QueActivity.this, ProductosCategorias.class);

            //Create information
            Bundle informacion= new Bundle();
            informacion.putParcelableArrayList("eventos", eventos);
            intent.putExtras(informacion);

并在另一个活动中接收它:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_productos_categorias);     
    lv = (ListView) findViewById(R.id.listaCategoriaElegida);
    Bundle informacionRecibida = getIntent().getExtras();               
    ArrayList<Evento> eventos =new ArrayList<Evento>();
    eventos= informacionRecibida.getParcelableArrayList("eventos");

我遇到了一个空指针异常。我已经调试过了,当我执行getParcelableArrayList(“eventos”)时,我得到了NULL,也就是说,我的arraylist eventos为空,因此我没有收到任何信息。
希望能得到帮助。

1
你必须将bundle放入intent中。 - njzk2
此外,这段代码 informacion.putParcelableArrayList("eventos", ArrayList<Eventos> eventos); 甚至无法编译通过,所以我不认为这是您正在使用的实际代码。 - njzk2
这不是我正在使用的实际代码。我已经将bundle放入了意图中。@Sameer的帖子不是重复的。 - n4h1n
https://dev59.com/eOo6XIcBkEYKwwoYSCg1#7400675 - Lalit Poptani
请查看此教程:http://xtreamcoder.com/pass-custom-arraylist/ - Androider
2个回答

3
这段代码
Bundle informacion= new Bundle();
informacion.putParcelableArrayList("eventos", ArrayList<Eventos> eventos);
intent.putExtras(informacion);

应该是:
Bundle informacion = new Bundle();
ArrayList<Eventos> mas = new ArrayList<Eventos>();
informacion.putSerializable("eventos", mas);
intent.putExtras(informacion);

确保您的Eventos结构像可序列化对象一样。
private class Eventos implements Serializable {

}

读取数值

ArrayList<Eventos> madd=getIntent().getSerializableExtra(key);

4
他询问了Parcelable,而你回答了Serializable,实际上并没有解决他代码中的问题,而是建议了一种效率远低于Parcelable的完全不同的方法。 - TOMKA
我支持 @TOMKA 的观点。请修正你的回答。 - Zen
2
Serializable 在安卓平台上性能非常差,建议使用 Parcelable。 - Michael Garner

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接