如何将数组从片段传递到片段

时间:2018-01-08 07:09:39

标签: android android-fragments bundle

我已将我的API响应数据添加到arraylist并尝试将该arraylist传递给下一个片段。但在第二个片段中我得到null result.below是我的代码。

第一个片段

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

                }
            });
        }

第二片段

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

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

2 个答案:

答案 0 :(得分:0)

试试这个把arraylist捆绑

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

获取arrayList

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

答案 1 :(得分:0)

试试这个 - :

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

在你的下一个活动中,这样做 - :

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