从另一个片段添加项目到recyclerView

时间:2016-07-24 05:15:41

标签: android android-fragments android-recyclerview

我想知道如何使用由customAdapter管理的recyclerView动态地将一个片段中的对象/包添加到另一个片段。

所以基本上我试图将一个对象从dialogFragment传递到另一个包含recyclerView的片段。

我的对话框片段点击添加按钮:

 @Override
 public void onClick(DialogInterface dialog, int which) {

 pof = new ProductForOrder(Integer.parseInt(input.getText().toString()),email,Integer.parseInt(serialNum), pTitle, imgUrl);
 cartFragment = new CartFragment();
 cartFragment.setList(pof);
 Toast.makeText(getActivity(), "Item added", Toast.LENGTH_SHORT).show();
  }

在我的cartFragment中,我尝试处理收到的对象,并通知适配器有关更改。

cartFragment:

public class CartFragment extends  Fragment implements ListAdapter.OnItemClickListener {

private FloatingActionButton mSharedFab;

private List<ProductForOrder> forOrderArrayList = new ArrayList<>();
private RecyclerView recyclerView;
private ListAdapter mAdapter;

public CartFragment() {
    // Required empty public constructor
}


public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState){
    View view = inflater.inflate(R.layout.fragment_cart, container, false);

    recyclerView = (RecyclerView) view.findViewById(R.id.list_recycler);

    mAdapter = new ListAdapter(this, forOrderArrayList, getActivity());
    RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
    recyclerView.setLayoutManager(mLayoutManager);
    recyclerView.setItemAnimator(new DefaultItemAnimator());
    recyclerView.setAdapter(mAdapter);


    //setList();

    return view ;
}

public void setList(ProductForOrder pof)
{

    forOrderArrayList.add(pof);
    mAdapter.notifyDataSetChanged();

}

毫不奇怪,我得到npe异常(尝试在空对象引用上调用接口方法'boolean java.util.List.add(java.lang.Object)',即使我确实得到了我的目标对话框,但我无法将其添加到cartFragment中的recyclerView。

任何建议都会受到赞赏,谢谢!

0 个答案:

没有答案