In order for a Bundle to pass non-primitive types, they must implement the Serializable or Parcelable .
The implementation of Serializable is simpler but, in android,
can create performance problems.
The implementation of Parcelable might at first glance seem complicated, but only laborious (1) .
Implementation example:
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 pass using:
intent.putExtra("DeviceEntity", DeviceEntity);
To receive:
Bundle b = getIntent().getExtras();
DeviceEntity deviceEntity = b.getParcelable("DeviceEntity");
(1) - If you are using Android Studio there is a possibility that it will do the job for you.
After adding implements Parcelable
, in the class declaration, place the cursor on it and use alt + enter . In the menu that opens choose Add Parcelable Implementation .