将ArrayList传递给Activity

时间:2016-09-17 12:24:20

标签: android android-intent android-activity arraylist serializable

我有ArrayListCustomInput个对象和DataWrapper类,其中包含ArrayList的getter和setter。我想将DataWrapper从非活动类传递给Activity类。我尝试过实现Serializable,但是我得到了 Parcelable遇到ioexception,因为 NotSerializableException 而编写了可序列化的对象

DataWrapper.java

public class DataWrapper implements Serializable {
    private static final long serialVersionUID = 1L;
private ArrayList<CustomInput> customInputs;

public void setFields(ArrayList<CustomInput> data) {
    this.customInputs = data;
}

public ArrayList<CustomInput> getFields() {
    return this.customInputs;
}
}

非活动类

public void showActivity() {
    Intent intent = new Intent(request, ActivityKorak.class);
    intent.putExtra("title", title);
    DataWrapper dw = new DataWrapper();
    dw.setFields(fields);
    intent.putExtra("data", dw);

    request.startActivity(intent);
}

ActivityKorak.class-&GT;的onCreate()

    Intent intent = getIntent();
    String title = intent.getStringExtra("title");
    DataWrapper dw = (DataWrapper) intent.getSerializableExtra("data");
    ArrayList<CustomInput> fields = dw.getFields();

2 个答案:

答案 0 :(得分:1)

无需创建新类 DataWrapper.java 。因为 ArrayList 是可序列化的。

非活动类

public void showActivity() {
    Intent intent = new Intent(request, ActivityKorak.class);
    intent.putExtra("title", title);
    intent.putExtra("data", fields);

    request.startActivity(intent);
}

<强> ActivityKorak.class-&GT;的onCreate()

    Intent intent = getIntent();
    String title = intent.getStringExtra("title");
    DataWrapper dw = (DataWrapper) intent.getSerializableExtra("data");
    ArrayList<CustomInput> fields = dw.getFields();

答案 1 :(得分:0)

嗨,请检查我们如何在意图中发送arraylist

ArrayList<HashMap<String, String>> aldata = new ArrayList<HashMap<String, String>>();

我假设这里的数据已添加到你的arraylist中,请检查

发送数据并开始其他活动,

Intent intent = new Intent(this,AbcActivity.class);
intent.putExtra("aldata", aldata_TaxiLine);
startActivity(intent);

在下一个活动中获取数据,

ArrayList<HashMap<String, String>> aldata1;

并在你的oncreate中调用它

    aldata = (ArrayList<HashMap<String, String>>) getIntent()
            .getSerializableExtra("aldata");

希望这会对你有所帮助。