【问题标题】:How to pass arrayList of a class object in another activity?如何在另一个活动中传递类对象的arrayList?
【发布时间】:2014-04-19 13:37:39
【问题描述】:
ArrayList <Car> CarList = new ArrayList<Car>();  
Car carItems= new Car(carno, cartype, date, arriveTime, carcost);   
CarList .add(carItems);

现在我想通过 Intent 传递 carList?

【问题讨论】:

    标签: android


    【解决方案1】:

    用于传递对象:

    Bundle bundle = new Bundle();
    ArrayList <Car> CarList = new ArrayList<Car>();  
    Car carItems= new Car(carno, cartype, date, arriveTime, carcost);   
    CarList.add(carItems); 
    bundle.putSerializable("carList",carList);
    intent.putExtras(bundle);
    

    用于检索:

    ArrayList <Car> CarList = getIntent().getSerializableExtra("carList");
    

    确保Car 是可序列化的:

    public class Car implements Serializable {
    
    }
    

    【讨论】:

    • 显示错误 Intent 类型中的 putExtra(String, boolean) 方法不适用于参数 (String, List)
    • 你有没有让你的Car类实现Parcelable
    • public class Car 实现 Parcelable 我已经实现了 public int describeContents(), public void writeToParcel(Parcel dest, int flags)
    【解决方案2】:

    看来您实际上必须将 Car 设为 Parcelable。

    要将其添加到 Intent,请使用 putParcelableArrayListExtra(String name, ArrayList&lt;? extends Parcelable&gt; value)

    编辑

    要在其他活动中获取列表,请在onCreateonNewIntent 中执行此操作:

    Intent i = getIntent();
    ArrayList<Car> cars = i.getParcelableArrayListExtra("extraKeyUsedWithPutExtra");
    

    【讨论】:

    • 嗨,如何在另一个活动中获取该列表?
    • 我添加了有关如何从另一个活动中获取列表的信息。
    【解决方案3】:

    让它变得清晰,非常容易。

    看看这个帖子:Arraylist in parcelable object

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-16
    • 2012-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多