How can I make my custom objects Parcelable?

后端 未结 11 2551
旧巷少年郎
旧巷少年郎 2020-11-21 07:40

I\'m trying to make my objects Parcelable. However, I have custom objects and those objects have ArrayList attributes of other custom objects I have made.

相关标签:
11条回答
  • 2020-11-21 08:11

    I have found simplest way to create Parcelable class

    0 讨论(0)
  • 2020-11-21 08:12

    1. Import Android Parcelable code generator

    2. Create a class

    public class Sample {
        int id;
        String name;
    }
    

    3. Generate > Parcelable from menu

    Done.

    0 讨论(0)
  • 2020-11-21 08:14

    It is very easy, you can use a plugin on android studio to make objects 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];
        }
    };}
    
    0 讨论(0)
  • 2020-11-21 08:16

    To put: bundle.putSerializable("key",(Serializable) object);

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

    0 讨论(0)
  • 2020-11-21 08:20

    Now you can use Parceler library to convert your any custom class in parcelable. Just annotate your POJO class with @Parcel. e.g.

        @Parcel
        public class Example {
        String name;
        int id;
    
        public Example() {}
    
        public Example(int id, String name) {
            this.id = id;
            this.name = name;
        }
    
        public String getName() { return name; }
    
        public int getId() { return id; }
    }
    

    you can create an object of Example class and wrap through Parcels and send as a bundle through intent. e.g

    Bundle bundle = new Bundle();
    bundle.putParcelable("example", Parcels.wrap(example));
    

    Now to get Custom Class object just use

    Example example = Parcels.unwrap(getIntent().getParcelableExtra("example"));
    
    0 讨论(0)
提交回复
热议问题