我实现了一个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”)时,我已经对它进行了debbuged并且我得到了NULL,我的意思是,我的arraylist eventos是null,所以,我没有收到任何信息。
任何帮助都会很棒
答案 0 :(得分: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);
答案 1 :(得分:1)
Parcelable在性能方面和其他功能方面要比序列化好得多。
参考此链接:
http://www.3pillarglobal.com/insights/parcelable-vs-java-serialization-in-android-app-development