如何将自定义对象的数组列表从一个 java 类传递到另一个 java 类? [英] How do I pass arraylist of a custom object from one java class to another?
问题描述
我有一个自定义对象的 Arraylist
.我试图将它从一个 java 文件传递到另一个.我尝试了 putExtra
方法和 Parcelable
选项;但我无法理解 Parcelable
.
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
.
这是我的自定义对象:
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;
}
}
这是我发送ArrayList
的代码:
Intent intent = new Intent(BluetoothLeService.this,HomePageFragment.class);
intent.putExtra("id", data_id);
intent.putExtra("value", list);
这里的list"指的是ArrayList
.
Here "list" refers to the ArrayList
.
推荐答案
Serializable
和 Parcelable
不是一回事,尽管它们服务于相同的目的.此帖子包含 Parcelable 对象的示例.
Serializable
and Parcelable
are not the same thing, although they serve the same purpose. This post contains an example of the Parcelable object.
您要创建的所有 Parcelable 对象都应遵循所采用的模式,仅更改 writeToParcel
和 AddValues(Parcel in)
方法.这两个方法应该互相映射,如果writeToParcel
写一个int
然后一个string
,构造函数应该读一个int
然后是一个 string
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
可包裹
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];
}
};
}
现在将列表添加到 Intent extra 应该很简单
Adding the list to an Intent extra should be simple now
额外添加列表
ArrayList<AddValue> list = new ArrayList<>();
Intent intent = new Intent(BluetoothLeService.this,HomePageFragment.class);
intent.putExtra("arg_key", list);
获取额外列表
ArrayList<AddValues> list = (ArrayList<AddValues>) intent.getSerializableExtra("arg_key");
顺便说一句,您可以使用 Pair
对象而不是创建 AddValues
对象.这不会影响答案,但可能很高兴知道.
As an aside, you can use the Pair<Integer, String>
object instead of creating an AddValues
object. This doesn't affect the answer, but might be nice to know.
这篇关于如何将自定义对象的数组列表从一个 java 类传递到另一个 java 类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!