如何在Android中将ArrayList <custom_object>从一个活动传递到另一个活动?</custom_object>

时间:2012-11-30 01:16:41

标签: android-intent arraylist

我正在尝试将自定义对象从一个活动发送到另一个活动,但是当我调用启动活动时它会崩溃。

以下是我使用的代码段。

我的活动实施Serializable

ArrayList<CUSTOM_OBJECT> Cus_Obje_arraylist = new ArrayList<CUSTOM_OBJECT>();

这是我的意图:

Intent inte = new Intent(getApplicationContext(), ListActivity.class); `
inte.putExtra("list",Cus_Obje_arraylist);`
startActivity(inte);

请告诉我为什么会崩溃或我可以使用哪种替代方式?

2 个答案:

答案 0 :(得分:7)

我可以提出一个建议。我在我的项目中这样做。

1.实现单例类作为传递对象的桥。 (希望你知道什么是单身人士,我不知道,加上评论告诉我。

class BridgeClass {
    private BridgeClass() {}

    static BridgeClass obj = nil;
    public BridgeClass instance() {
         if (obj == nil) obj = new BridgeClass();
         return obj;
    }

    public ArrayList<CUSTOM_OBJECT> cache;
 }

2.在from活动中,

BridgeClass.instance().cache = Cus_Obje_arraylist;

3.然后在to活动中,您可以从桥类中获取它。

ArrayList<CUSTOM_OBJECT> Cus_Obje_arraylist = BridgeClass.instance().cache;

答案 1 :(得分:0)

您需要创建Parcelable对象以从一个活动传递自定义数组列表 另一种行为。

然后使用此api将其放入Bundle对象。

putParcelableArrayList(key, value);
getParcelableArrayList(key);

===发件人===

ArrayList<Custom> ar = new ArrayList<Custom>();
Bundle bundle = new Bundle("test");

bundle.putParcelableArrayList("key", ar);
Intent intent = new Intent(this, anotherActivity.class);
intent.putBundle(bundle);

===接收者===

Bundle bundle = getIntent().getBundleExtra("test");
ArrayList<Custom> ar = bundle.getParcelableArrayList("key");

如果您有任何疑问,请发表评论。

相关问题