user8164155
user8164155

Reputation: 127

How to pass array bundle from fragment to fragment

I have added my API response data into arraylist and tried to pass that arraylist to next fragment.but in second fragment i'm getting null result.below is my code.

First fragment

 ArrayList<String> productList;
 Bundle bundleProduct;

    public void getProduct(id){
        productList = new ArrayList<String>();
        bundleProduct = new Bundle();

            WebserviceAPI apiService =retrofit.create(WebserviceAPI.class);
            Call<ProductResponse> call = apiService.getproducts("getvalue",id);
            call.enqueue(new Callback<ProductResponse>() {
                @Override
                public void onResponse(Call<ProductResponse> call, Response<ProductResponse> response) {
                    ProductResponse result = response.body();
                    status=result.isStatus();

                    if(status){
                        productList.add(a.getProduct_name());
                        productList.add(a.getProduct_quantity());
                        productList.add(a.getOriginal_product_price());

                        bundleProduct.putStringArrayList("productList", productList);

                        SecondFragment secondFragment = new SecondFragment();
                            secondFragment.setArguments(bundleProduct);
                                getFragmentManager()
                                        .beginTransaction()
                                        .replace(R.id.fragment_switch, secondFragment)
                                        .commit();                            
                    }              

                }

                @Override
                public void onFailure(Call<ProductResponse> call, Throwable t) {                

                }
            });
        }

Second Fragment

ArrayList<String> ProductList =new ArrayList<String>();;

    if (getArguments() != null) {
                ProductList  =getArguments().getStringArrayList("productList");
                Log.d("ProductList","list "+ProductList);
            }
            else{
                Log.d("ProductList","null ");
            }

Upvotes: 1

Views: 1758

Answers (2)

Shivam Oberoi
Shivam Oberoi

Reputation: 1445

Try this-:

SecondFragment mfragment=new SecondFragment();
Bundle bundle = new Bundle();
bundle.putSerializable("productList", list);
mfragment.setArguments(bundle); //data being send to SecondFragment

And in your next activity do as this-:

ArrayList<String> list= (ArrayList<String>)getArguments().getSerializable("productList");

Upvotes: 1

Hemant Parmar
Hemant Parmar

Reputation: 3976

Try this put arraylist to bundle

Bundle bundle = new Bundle();
bundle.putSerializable("productList", list);

get arrayList

ArrayList<String> list= (ArrayList<String>)getArguments().getSerializable("productList");

Upvotes: 1

Related Questions