java 自定义对象数组,如何将自定义对象的数组列表从一个Java类传递到另一个Java类?...

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值