简体   繁体   中英

How to make an arraylist of arraylists parcelable in android

My problem is that I have an arraylist of arraylists with custom objects that needs to be passed from one activity to another.

Clearly, let's say I have something like:

ArrayList<ArrayList<Statement>> data;  

in one activity and I want to pass it to another. So, first what I have done is to make Statement implement the Parcelable class. Then in the first activity (sender) I call the putExtra() method by passing it the data . In the second activity (receiver) I call the getSerializableExtra() method to get data .

That works. But I have read that Parcelable would be better for efficiency etc. and so I tried to call putParcelableArrayListExtra() in the sender activity and the getParcelableArrayListExtra() method on the receiver activity. But when I do that, I get red underlines indicating sth. like

ArrayList< android.os.Parcelable > is required

in the first activity which is the sender I have the line:

Intent intent = new Intent(SenderActivity.this, ReceiverActivity.class);

intent.putParcelableArrayListExtra(SenderActivity.EXTRA_LISTOFSTATEMENTLISTS, dataListOfStatementLists);

In the receiver activity I have sth. like:

myList = ( ArrayList<ArrayList<Statement>>) getIntent().getParcelableArrayListExtra(EXTRA_LISTOFSTATEMENTLISTS);

What I need to fix ? I know the basics about how to send Parcelable objects from one activity to another. But that was all things like

ArrayList<ParcelableObject> data

I have never done it for nested data like this

ArrayList<ArrayList<ParcelableObject>>

I hope someone can help.

Thanks in advance

This is just another way to do it. I suppose you know how to get the values in other activity.

ArrayList<ArrayList<Statement>> data;
Bundle bundle = new Bundle();
bundle.putInt("size", data.size());
for (int i = 0; i < data.size(); i++) {
    bundle.putParcelableArrayList("item"+i, data.get(i));
}

Try this to send Data

Intent intent = new Intent(SenderActivity.this, ReceiverActivity.class);
Bundle bundle = new Bundle();
bundle.putParcelable("object", List);
in.putExtra("list", bundle);
startActivity(in);

For Recieving Data

Intent i=getIntent();
Bundle bundle= i.getBundleExtra("list");
ArrayList<Statement> list = bundle.getParcelable("object");

Every time you want to pass data from one activity to another one via Intent you have to make sure that the classes where you create the objects that you want to send are implementing Serializable , otherwise it won't work. Your problem could be something related to this so I recommend you to implement Serializable on your classes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM