我正在尝试将Firebase中的CategoryID从一个片段传递到另一个片段 使用ImageView单击,但单击ImageView时我的应用程序崩溃。
这是我的代码;
MenuFragment.java
FirebaseRecyclerAdapter<Category, MenuViewHolder> adapter;
viewHolder.setItemClickListener(new ItemClickListener() {
@Override
public void onClick(View view, int position, boolean isLongClick) {
CarListFragment cfragment= new CarListFragment ();
Bundle bundle = new Bundle();
bundle.putString("CategoryID",adapter.getRef(position).getKey());
cfragment.setArguments(bundle);
getFragmentManager().beginTransaction()
.replace(R.id.frame_main, cfragment, cfragment.getTag())
.addToBackStack(null)
.commit();
}
});
CarListFragment.java
String CategoryID="";
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v= inflater.inflate(R.layout.fragment_car_list, container, false);
Bundle bundle = this.getArguments();
if (bundle != null) {
CategoryID=getActivity().getIntent().getStringExtra("CategoryID");
}
if(!CategoryID.isEmpty()&& CategoryID!=null){
loadCarList(CategoryID);
}
return v;
}
logcat的
答案 0 :(得分:3)
使用bundle
因为它有数据
Bundle bundle = this.getArguments();
if (bundle != null) {
CategoryID = bundle.getString("CategoryID");
// ^^^^^^
}
而不是
CategoryID=getActivity().getIntent().getStringExtra("CategoryID");
因为getActivity().getIntent()
会为您提供之前用于开展活动的Intent
对象
答案 1 :(得分:3)
使用它:
CarListFragment cfragment= new CarListFragment ();
Bundle bundle = new Bundle();
bundle.putString("CategoryID", adapter.getRef(position));
cfragment.setArguments(bundle);
getFragmentManager().beginTransaction()
.replace(R.id.frame_main, cfragment, cfragment.getTag())
.addToBackStack(null)
.commit();
获取字符串:
String str = getArguments().getString("my_string");