How to pass ArrayList<Custom_Object> from one activity to another in Android?

萝らか妹 提交于 2020-01-05 21:04:32

问题


I am trying to send a custom object from one activity to another activity, but it's crashing when I call the start activity.

Below is the snippet I used.

My Activity implements Serializable

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

Here is my intent :

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

Please let me know why it's crashing or what alternate way I can use?


回答1:


I can give a suggestion. I do this in my project.

1.Implement a singleton class as the bridge to pass object. (Hopefully you know what's singleton, I you don't, add comment to tell me.

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.In the from activity,

BridgeClass.instance().cache = Cus_Obje_arraylist;

3.Then in the to activity, you can get it from the bridge class.

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



回答2:


You need to create the Parcelable object to pass the custom array list from one activity to the another actvity.

Then put it into the Bundle object using the this api.

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

=== Sender ===

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);

=== Receiver ===

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

If you have any question, comment it.



来源:https://stackoverflow.com/questions/13637625/how-to-pass-arraylistcustom-object-from-one-activity-to-another-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!