我试着让我的对象可打包。但是,我有自定义对象,这些对象具有我所做的其他自定义对象的ArrayList属性。

最好的方法是什么?


当前回答

1. 导入Android Parcelable代码生成器

2. 创建类

public class Sample {
    int id;
    String name;
}

3.从菜单生成> Parcelable

完成了。

其他回答

1. 导入Android Parcelable代码生成器

2. 创建类

public class Sample {
    int id;
    String name;
}

3.从菜单生成> Parcelable

完成了。

这很简单,你可以在android studio上使用一个插件来制作对象Parcelables。

public class Persona implements Parcelable {
String nombre;
int edad;
Date fechaNacimiento;

public Persona(String nombre, int edad, Date fechaNacimiento) {
    this.nombre = nombre;
    this.edad = edad;
    this.fechaNacimiento = fechaNacimiento;
}

@Override
public int describeContents() {
    return 0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {
    dest.writeString(this.nombre);
    dest.writeInt(this.edad);
    dest.writeLong(fechaNacimiento != null ? fechaNacimiento.getTime() : -1);
}

protected Persona(Parcel in) {
    this.nombre = in.readString();
    this.edad = in.readInt();
    long tmpFechaNacimiento = in.readLong();
    this.fechaNacimiento = tmpFechaNacimiento == -1 ? null : new Date(tmpFechaNacimiento);
}

public static final Parcelable.Creator<Persona> CREATOR = new Parcelable.Creator<Persona>() {
    public Persona createFromParcel(Parcel source) {
        return new Persona(source);
    }

    public Persona[] newArray(int size) {
        return new Persona[size];
    }
};}

我尝试使用Parcellable,时间很短,所以使用Gson如下。也许它能帮助到少数人…

PersonData personData;
BusinessData businessData;

以上两个都是模型对象。我想把它从loginactivity。class传递给mainactivity。class。Parcellable无法使用大型模型,需要时间进行修改。

startActivity(
    new Intent(LogInActivity.this, MainActivity.class)
    .putExtra("businessData", new Gson().toJson(businessData))
    .putExtra("personData", new Gson().toJson(personData))
);

在MainActivity.class中检索这些对象

BusinessData businessData = new Gson().fromJson(getIntent().getStringExtra("businessData"), BusinessData.class);
PresonData personData = new Gson().fromJson(getIntent().getStringExtra("personData"), PersonData.class);

在Android Studio中创建没有插件的Parcelable类

在你的类中实现Parcelable,然后把光标放在“implements Parcelable”上,然后按Alt+Enter并选择添加Parcelable实现(见图片)。就是这样。

将: bundle.putSerializable(“关键”,(序列化)对象);

得到: List<Object> obj = (List<Object>)((Serializable)bundle.getSerializable("key"));