Skip to content Skip to sidebar Skip to footer

Passing Object Array List Between Fragments In Android Development

I am trying to pass arraylist between fragments in Android development. This is the part where I tried to pass Transaction array list to another fragment: switch (menuItem.getItemI

Solution 1:

ArrayList<Transaction> transactionList = new ArrayList<>();

pass the transactionList to the bundle

Bundlebundle=newBundle();
bundle.putSerializable("key", transactionList);

and in the receiving fragment

ArrayList<Transaction> transactionList = (ArrayList<Transaction>)getArguments().getSerializable("key");

NOTE: to pass your bean class via bundle you have to implement serializable i.e

YourBeanClass implements Serializable

Solution 2:

add this gradle in your build.gradlecompile 'com.google.code.gson:gson:2.7'

Stringstr = new Gson().toJson(arrayList);
bundle.putStrin("str",str);

and destination fragemnt

String str = bundle.getString("str");

arrayList = new Gson().fromJson(str,ArrayList.class);

Solution 3:

1.You can either pass it by converting into json as specified by @Bhupat.

2.Another way is you make your Transaction class parcelable and the use

b.putParcelableArrayList("list",your_list);

for getting list

your_list = getArguments().getParcelableArrayList("list");

EDIT you have too sepcigy type token for getting it back

 transactionlist = new Gson().fromJson(str,  new TypeToken<List<type of the list passed>>);

In your case new TypeToken<List<Transaction>>

Solution 4:

Instead of implementing Serializable, you should make your Transaction class implement Parcelable. Parcelable is the fastest serialization mechanism you can use on Android, it's faster than Serializable or JSON transformation and uses less memory.

Post a Comment for "Passing Object Array List Between Fragments In Android Development"