Fiona Muthoni
Fiona Muthoni

Reputation: 85

Pass data from Firebase from one fragment to another

I'm trying to pass a CategoryID from Firebase from one fragment to another using an ImageView Click but my app crashes when an ImageView is clicked.

Here is my code;

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

enter image description here

Upvotes: 0

Views: 929

Answers (2)

Konstantin Shendenkov
Konstantin Shendenkov

Reputation: 287

use this:

    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();

get String:

    String str = getArguments().getString("my_string");

Upvotes: 3

Pavneet_Singh
Pavneet_Singh

Reputation: 37404

Use bundlebecause it has the data

Bundle bundle = this.getArguments();
if (bundle != null) {
    CategoryID = bundle.getString("CategoryID");
    //           ^^^^^^
}

instead of

CategoryID=getActivity().getIntent().getStringExtra("CategoryID");

because getActivity().getIntent() will give you an Intent object which was previously used to start your activity

Upvotes: 3

Related Questions