Android: how to pass ArrayList<object> from an activity to another

你离开我真会死。 提交于 2019-12-31 02:55:41

问题


The object in the arraylist is defined in an external library. The object contains some int values and also a float[].

How can I pass all the ArrayList from an activity to another? Thanks!

By the way, I do not have the control of the object class.


回答1:


It depends on the type of object that's in the array list. If you have control over it and can have it implement Parcelable, then you can use Intent.putParcelableArrayListExtra.

Another approach is to extend Application and store your ArrayList there. It then doesn't need to be passed in the Intent, and all activities in the application can access it by calling getApplication(). The Application object will persist for the life of the application, as will any data stored in it.

EDIT:

To use an Application object for this:

  1. Write a class (let's call it MyApplication) that extends android.app.Application. Declare a field (let's call it array) to hold your array list.
  2. Specify the name MyApplication in the manifest's <application> tag. An instance of MyApplication will be created by the system when it creates the process for your app.
  3. Any activity that wishes to access the field can use ((MyApplication) getApplication()).array. You initialize it in the first activity and retrieve it in the second.

Another completely different approach is to declare a static singleton in some class. The docs actually recommend this over subclassing Application as being more modular. It's kind of a hack because it's basically declaring a global variable. But I suppose it's no more of a hack than putting random data in an Application object.




回答2:


Intent intent = new Intent(this, TargetActivity.class);
intent.putExtra("nameOfArray",YOUR_ARRAY_LIST);
startActivity(intent);


来源:https://stackoverflow.com/questions/6433834/android-how-to-pass-arraylistobject-from-an-activity-to-another

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