Passing object array list between fragments in Android development

前端 未结 4 1548
梦如初夏
梦如初夏 2021-01-14 09:58

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         


        
相关标签:
4条回答
  • 2021-01-14 10:08
    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

    0 讨论(0)
  • 2021-01-14 10:13

    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);
    
    0 讨论(0)
  • 2021-01-14 10:22

    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>>

    0 讨论(0)
  • 2021-01-14 10:23

    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.

    0 讨论(0)
提交回复
热议问题