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:
sw
ArrayList<Transaction> transactionList = new ArrayList<>();
pass the transactionList to the bundle
Bundle bundle = new Bundle();
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
add this gradle in your build.gradle
compile 'com.google.code.gson:gson:2.7'
String str = new Gson().toJson(arrayList);
bundle.putStrin("str",str);
and destination fragemnt
String str = bundle.getString("str");
arrayList = new Gson().fromJson(str,ArrayList.class);
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>>
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.