Pass arraylist of user defined objects to Intent android

瘦欲@ 提交于 2019-11-26 17:47:08
Simon Dorociak

I have given implements serializable in both the classes, but am getting unable to marshall.. run time error in the calling function at line start activity. Please help how to proceed with!

Since you are using Serializable, you cannot do it like now. I suggest you to wrap your ArrayList to class for example named DataWrapper. This class also needs to implement Serializable and then you are able to pass ArrayList via Intent.

Example:

public class DataWrapper implements Serializable {

   private ArrayList<Parliament> parliaments;

   public DataWrapper(ArrayList<Parliament> data) {
      this.parliaments = data;
   }

   public ArrayList<Parliament> getParliaments() {
      return this.parliaments;
   }

}

And an usage:

Intent i = new Intent(...);
i.putExtra("data", new DataWrapper(yourArrayList));

and retrieving:

DataWrapper dw = (DataWrapper) getIntent().getSerializableExtra("data");
ArrayList<Parliament> list = dw.getParliaments();

Note:

There is also option to use Parcelable interface. If you will use it, you can put and retrieve your ArrayList with these methods:

intent.putParcelableArrayListExtra("key", ArrayList<T extends Parcelable> list);
getIntent().getParcelableArrayListExtra("key");


Generally is recommended to use Parcelable interface that is directly designated for passing objects through Activities but i usually use Serializable interface and it always make a trick.

Also be carefull about typos. You are putting object with key task and you should retrieve it with same key and not with tasklist.

Orkun Ozen

Implementation of Serializable is deemed low performant where as Parcelable is encouraged.

I had the exact same question and while still hassling with the Parcelable, I found out that the static variables are not such a bad idea for the task.

You can simply create a

public static ArrayList<Parliament> myObjects = .. 

and use it from elsewhere via MyRefActivity.myObjects

I was not sure about what public static variables imply in the context of an application with activities. If you also have doubts about either this or on performance aspects of this approach, refer to:

Cheers.

Make your object class Parcelable later try to use

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