How to pass ArrayList from one activity to

2019-07-25 16:08发布

问题:

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.