Passing ArrayList with objects to new Activity?

2019-01-26 08:15发布

I'm trying to pass an ArrayList from my first Activity to the next one. Basically, the first activity parses an XML file and creates an ArrayList with objects inside. What I want to do is send that ArrayList to my second activity and show some of the object data in a ListView.

I thought of doing this with an intent, but it looks like only primitive datatypes are usually passed through intents. Is this right?

If so, what would be a better solution to pass the data? Certainly Android must provide something to be able to do this kind of thing.

Any help/code examples are really appreciated..

Thanks

EDIT:

I solved this by first creating and calling the intent, and only parsing the XML in the Activity that I called. This way I didn't need to pass the objects anymore. But for those interested, you can read about how to pass data through activities, here.

6条回答
时光不老,我们不散
2楼-- · 2019-01-26 09:03

You can pass a String List using putStringArrayListExtra(String name, ArrayList<String> value) if it is strings. Or, you could serialize List and then use putExtra(String name, Serializable value).

If you don't want to/can't use the above, you could use a central util class with a static reference to the List. Just set it in your first Activity and get it in the second.

查看更多
beautiful°
3楼-- · 2019-01-26 09:09

You can set the scope of ArrayList at application level or you can do this using parcelable.

查看更多
地球回转人心会变
4楼-- · 2019-01-26 09:10

I would do a toString on the array and pass it as an extra by doing a intent.putExtra("label". array.toString()); and then just recover it in the new activity.

查看更多
虎瘦雄心在
5楼-- · 2019-01-26 09:13

Complex types may be passed by means of Parcelable. An example is in this question:

Help with passing ArrayList and parcelable Activity

查看更多
倾城 Initia
6楼-- · 2019-01-26 09:15

I made this trick to send from first Activity to second.

The first activity

ArrayList<String> mylist = new ArrayList<String>();  
Intent intent = new Intent(ActivityName.this, Second.class);
intent.putStringArrayListExtra("key", mylist);
startActivity(intent);

The second activity

To retrieve

ArrayList<String> list =  getIntent().getStringArrayListExtra("key");
查看更多
男人必须洒脱
7楼-- · 2019-01-26 09:22

This could be totally bad practice and I wouldn't know any better, but you could declare the ArrayList as public and static. Then just access it with Activity.ArraylistName.

查看更多
登录 后发表回答