【问题标题】:Pass Arraylist of objects in another activity在另一个活动中传递对象的 Arraylist
【发布时间】:2014-10-29 06:14:43
【问题描述】:

我正在尝试在另一个活动中发送对象的数组列表。我检查了很多关于这个主题的文章,我正在使用 parcelable,但我被困在无法发送对象的地方。我尝试了很多事情。这就是我正在尝试的事情。

public class ParcalableForm implements Parcelable {

private ArrayList<form> from;


public ParcalableForm (ArrayList<form> choices) {
    this.from = choices;
}

public ParcalableForm (Parcel parcel) {
    this.from = parcel.readArrayList(null);
}



@Override
public int describeContents() {
    return 0;
}

// Required method to write to Parcel
@Override
public void writeToParcel(Parcel dest, int flags) {
    dest.writeList(from);
}

// Method to recreate a Question from a Parcel
public static Creator<ParcalableForm> CREATOR = new Creator<ParcalableForm>() {

    @Override
    public ParcalableForm createFromParcel(Parcel source) {
        return new ParcalableForm(source);
    }

    @Override
    public ParcalableForm[] newArray(int size) {
        return new ParcalableForm[size];
    }

};

}

这是实现 Parcelable 的 Parcelable 类。我正在尝试将 Arraylist 形式发送到另一个活动。

  Intent i = new Intent(UserPage.this,Form.class);

  Bundle extras = new Bundle();
  System.out.println("I found a form :- ");
  ParcalableForm p=new ParcalableForm(f1.attr);
  i.putExtra("geopoints", p);
  startActivity(i);

这是将对象发送到其他活动的类。

Bundle extras = getIntent().getExtras();
ParcalableForm po =  new ParcalableForm(extras.getParcelableArrayList("geopoints"));

这是我不知道如何获取对象/Arraylist 的部分。我尝试了很多方法但没有运气。有什么想法吗?

【问题讨论】:

  • 我猜你有一个自定义表单类。该类也必须实现 Parcelable。
  • 是的,我也这样做了..不工作
  • 1.使Form实现parcelable,2.摆脱ParcalableForm类。 3. 在意图传递数组列表时使用put/getParcelableArrayListExtra。详情见我的回答

标签: java android android-activity arraylist


【解决方案1】:

将数据传递给另一个活动

 ArrayList<Animal> animals = new ArrayList<Animal>();
//fill your list with animals here

i.putExtra("animals", animals);

接收此数据

ArrayList<Animal> animals = (ArrayList<Animal>) getIntent()
                        .getSerializableExtra("animals");

【讨论】:

    【解决方案2】:

    如果您想要传递ArrayList&lt;Form&gt;,则使用getParcelableArrayListExtra
    通常,请按照以下步骤操作:

    • 正确设置Form 课程implement Parcelable
    • 在活动发送意图中:

      // ArrayList<Form> myList - data to send; intent.putParcelableArrayListExtra("geopoints", myList);

    • 在接收活动中:

      ArrayList&lt;Form&gt; myReceivedList = getIntent().getParcelableArrayListExtra("geopoints");

    不要忘记空值/完整性检查。

    希望有帮助

    【讨论】:

    • 我收到一个错误Cannot cast from ArrayList&lt;Parcelable&gt; to ArrayList&lt;Location&gt;
    猜你喜欢
    • 1970-01-01
    • 2014-04-19
    • 1970-01-01
    • 2012-11-16
    • 1970-01-01
    • 2023-01-11
    • 2013-01-12
    • 1970-01-01
    • 2018-10-10
    相关资源
    最近更新 更多