如何通过Intents传递List <customobject>

时间:2017-02-02 09:55:47

标签: java android list android-intent arraylist

我有自定义对象的ArrayList

ArrayList<AvailableCountry>
        listAvailableCountries = new ArrayList();

我有两个AvailableCountry对象

AvailableCountry obj1=new AvailableCountry();
AvailableCountry obj2=new AvailableCountry();

然后我加入了arraylist

listAvailableCountries.add(obj1);
listAvailableCountries.add(obj2);

这是自定义对象类

public class AvailableCountry {

@SerializedName("Disabled")
@Expose
private Boolean disabled;
@SerializedName("Selected")
@Expose
private Boolean selected;
@SerializedName("Text")
@Expose
private String text;
@SerializedName("Value")
@Expose
private String value;

public Boolean getDisabled() {
    return disabled;
}

public void setDisabled(Boolean disabled) {
    this.disabled = disabled;
}

public Boolean getSelected() {
    return selected;
}

public void setSelected(Boolean selected) {
    this.selected = selected;
}

public String getText() {
    return text;
}

public void setText(String text) {
    this.text = text;
}

public String getValue() {
    return value;
}

public void setValue(String value) {
    this.value = value;
}

}

现在我想把这个arraylist从Activity A传递给Activity B. 然后我想在活动B中收到 我怎样才能完成这项任务。

2 个答案:

答案 0 :(得分:1)

1)首先实现自定义对象类的接口

public class AvailableCountry implements Serializable {

@SerializedName("Disabled")
@Expose
private Boolean disabled;
@SerializedName("Selected")
@Expose
private Boolean selected;
@SerializedName("Text")
@Expose
private String text;
@SerializedName("Value")
@Expose
private String value;

public Boolean getDisabled() {
    return disabled;
}

public void setDisabled(Boolean disabled) {
    this.disabled = disabled;
}

public Boolean getSelected() {
    return selected;
}

public void setSelected(Boolean selected) {
    this.selected = selected;
}

public String getText() {
    return text;
}

public void setText(String text) {
    this.text = text;
}

public String getValue() {
    return value;
}

public void setValue(String value) {
    this.value = value;
}

}

2)将arrayList从A类发送到B类

Intent intent =new Intent(A.this,B.class);
intent.putExtra("listCountry", (Serializable) listAvailableCountries);
startActivity(intent)

3)接受B组中的arraylist

ArrayList<AvailableCountry>listAvailableCountries = (ArrayList<AvailableCountry>) getIntent().getSerializableExtra("listCountry");

答案 1 :(得分:0)

使用Gson我们可以轻松共享数据

compile 'com.google.code.gson:gson:2.4'

在A.class

中发送
 Intent intent = new Intent(A.this, B.class);
    String favJSONString = new Gson().toJson(listAvailableCountries);
    intent.putExtra("listAvailableCountries", favJSONString);
    startActivity(intent);

并像这样接收B.class

try {
        Type type = new TypeToken<List<AvailableCountry>>() {
        }.getType();
        ArrayList<AvailableCountry> listAvailableCountries  = new Gson().fromJson(getIntent().getStringExtra("listAvailableCountries"), type);
    } catch (Exception e) {
        e.printStackTrace();
    }