How to pass custom object arraylist from activity to fragment with instance

假如想象 提交于 2021-01-29 02:50:00

问题


I am using viewpager and creating fragments and i want to pass the arraylist. So i have tried the below things:

MainActivity:

 private ArrayList<customers> mArrayList = null;

  ViewPagerAdapter adapter = new ViewPagerAdapter(MainActivity.this.getSupportFragmentManager());

  adapter.addFrag(NewCustomer.newInstance(mArrayList ), "NewCustomer");

Now in fragment class i am creating instance:

 public static final ArrayList<customers> data = new ArrayList<customers>();

 public static final NewCustomer newInstance(ArrayList<customers> mArrayList) {

        NewCustomer f = new NewCustomer();
        Bundle bdl = new Bundle(1);
        bdl.putParcelableArrayList(data, mArrayList);
        f.setArguments(bdl);
        return f;
    }

But this is not working. It is showing error on bdl.putParcelableArrayList I want to get arraylist and store into the local arraylist of that class.

How can i get the arraylist with my custom object ?


回答1:


Can you try ?

public static final NewCustomer newInstance(ArrayList<customers> mArrayList) {

        NewCustomer f = new NewCustomer();
        Bundle bdl = new Bundle(1);
        this.data = mArrayList; // assign its Value
        bdl.putParcelableArrayList(data, mArrayList);
        f.setArguments(bdl);
        return f;
    }

this.data = mArrayList will assign value to the current member variable of fragment. Now it can we be accessed in current fragment.




回答2:


The first parameter you are passing is wrong. Check the definition:

putParcelableArrayList(String key, ArrayList<? extends Parcelable> value)

Define the key as following in your fragment:

public static final String KEY;

To get the arraylist as local variable in your fragment use following code:

@Override
public void onStart() {
    super.onStart();
    Bundle arguments = getArguments();
    ArrayList<customers> customer_list = arguments.getParcelable(KEY);
}



回答3:


please check that your model class "NewCustomer" implements Parcelable.



来源:https://stackoverflow.com/questions/41376246/how-to-pass-custom-object-arraylist-from-activity-to-fragment-with-instance

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