Search code examples
androidandroid-fragmentsandroid-viewpagerandroid-bundle

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


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 ?


Solution

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