Passing ArrayList <CustomObject> Between Actions
I implemented the 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 try to pass an arrayList to another activity: I'me overwrites onItemClick, and I pass the information as follows:
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 get it in another action:
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 get a null pointer exception. I am debbuged and I get NULL when I execute getParcelableArrayList ("eventos"), I mean that my arraylist eventos are null, so I don't get any information.
Any help would be great
This code
Bundle informacion= new Bundle(); informacion.putParcelableArrayList("eventos", ArrayList<Eventos> eventos); intent.putExtras(informacion); Must be
Bundle informacion = new Bundle(); ArrayList<Eventos> mas = new ArrayList<Eventos>(); informacion.putSerializable("eventos", mas); intent.putExtras(informacion); and make sure your Eventos structure is as a serializable object
private class Eventos implements Serializable { } Reading values
ArrayList<Eventos> madd=getIntent().getSerializableExtra(key); Parcelable is much better than serialization in terms of performance and other features.
link:
http://www.3pillarglobal.com/insights/parcelable-vs-java-serialization-in-android-app-development