So that a Bundle can pass not primitive types they must implement the interface Serializable or Parcelable.
The implementation of Serializable is simpler but, no android,
can create performance problems.
The implementation of Parcelable may at first glance seem complicated, but it’s just laborious(1).
Example of implementation:
public class DeviceEntity implements Parcelable{
private long id;
private String name;
private String codigo;
private String number;
private boolean isSelected;
public DeviceEntity(long id, String name, String codigo, String number, boolean isSelected){
this.id = id;
this.name = name;
this.codigo = codigo;
this.number = number;
this.isSelected = isSelected;
}
//Parcelable implementation
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
// Necessitamos de escrever cada um dos campos no parcel.
// Quando formos ler do parcel estes são retornados pela mesma ordem
dest.writeLong(id);
dest.writeString(name);
dest.writeString(codigo);
dest.writeString(number);
dest.writeByte((byte)(isSelected ? 1 : 0));
}
public static final Parcelable.Creator<DeviceEntity> CREATOR = new
Parcelable.Creator<DeviceEntity>() {
@Override
public DeviceEntity createFromParcel(Parcel source) {
return new DeviceEntity(source);
}
@Override
public DeviceEntity[] newArray(int size) {
throw new UnsupportedOperationException();
//return new DeviceEntity[size];
}
}
;
//Construtor usado pelo android para criar a nossa classe, neste caso DeviceEntity
public DeviceEntity(Parcel source) {
//Os valores são retornados na ordem em que foram escritos em writeToParcel
id = source.readLong();
name = source.readString();
codigo = source.readString();
number = source.readString();
isSelected = source.readByte() != 0;
}
//Getters
public long getId() {
return id;
}
public String getName() {
return name;
}
public String getCodigo() {
return codigo;
}
public String getNumber() {
return number;
}
public boolean isSelected() {
return isSelected;
}
}
To use:
intent.putExtra("DeviceEntity", DeviceEntity);
To receive:
Bundle b = getIntent().getExtras();
DeviceEntity deviceEntity = b.getParcelable("DeviceEntity");
(1) - If you are using Android Studio there is possibility that it will do the work for you.
After including implements Parcelable
, in the class declaration, place the cursor over it and use alt + enter. In the menu that opens choose Add Parcelable Implementation.
As @ramaral said, Serializable could be implemented but with performance problems. I leave here a reference that helped me when I was in the dilemma between using Parcelable and Serializable. Blog Developer Phil
– emanuelsn