I have an Arraylist of custom objects. I am trying to pass it from one java file to another. I tried the putExtra method and the Parcelable option; but I'm unable to understand Parcelable.
Here's my custom object:
public class AddValues implements Serializable{
public int id;
String value;
public AddValues(int id, String value)
{
this.id = id;
this.value = value;
}
@Override
public String toString() {
String result = "id = "+id+","+" value = "+value;
return result;
}
public int getid()
{
return this.id;
}
public String getvalue()
{
return this.value;
}
}
And here's my code to send the ArrayList:
Intent intent = new Intent(BluetoothLeService.this,HomePageFragment.class);
intent.putExtra("id", data_id);
intent.putExtra("value", list);
Here "list" refers to the ArrayList.
解决方案
Serializable and Parcelable are not the same thing, although they serve the same purpose. This post contains an example of the Parcelable object.
The pattern employed should be followed for all Parcelable objects you want to create, changing only the writeToParcel and AddValues(Parcel in) methods. These two methods should mirror eachother, if writeToParcel writes an int then a string, the constructor should read an int then a string
Parcelable
public class AddValues implements Parcelable{
private int id;
private String value;
// Constructor
public AddValues (int id, String value){
this.id = id;
this.value= value;
}
// Parcelling part
public AddValues (Parcel in){
this.id = in.readInt();
this.value= in.readString();
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(id);
dest.writeString(value);
}
public final Parcelable.Creator CREATOR = new Parcelable.Creator() {
public AddValues createFromParcel(Parcel in) {
return new AddValues(in);
}
public AddValues[] newArray(int size) {
return new AddValues[size];
}
};
}
Adding the list to an Intent extra should be simple now
Put List extra
ArrayList list = new ArrayList<>();
Intent intent = new Intent(BluetoothLeService.this,HomePageFragment.class);
intent.putExtra("arg_key", list);
Get List extra
ArrayList list = (ArrayList) intent.getSerializableExtra("arg_key");
As an aside, you can use the Pair object instead of creating an AddValues object. This doesn't affect the answer, but might be nice to know.