Passing ArrayList Between Activities

2019-03-21 14:02发布

问题:

i've implemented a Parcelable class:

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

In my activity, i'm trying to pass an arrayList to an other activitie: I'me overwriten onItemClick and i'm passing the information this way:

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);

and receiving it in the other activity:

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");

I'm getting a null pointer exception. I've debbuged it and i'm getting NULL when i execute the getParcelableArrayList("eventos"), i mean, my arraylist eventos is null, so, i'm receiving no information.

Any help will be great

回答1:

This code

Bundle informacion= new Bundle();
informacion.putParcelableArrayList("eventos", ArrayList<Eventos> eventos);
intent.putExtras(informacion);

Should be

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

and Make sure your Eventos structure like a serializable object

private class Eventos implements Serializable {

}

Reading Values

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


回答2:

Parcelable is much better than serialization in a performance wise and other features.

refer this link:

http://www.3pillarglobal.com/insights/parcelable-vs-java-serialization-in-android-app-development