abirami bhargavi
abirami bhargavi

Reputation: 49

how to pass data between fragments from recyclerview adapter

I have two fragments and the first fragment has a recyclerview adapter were i want to pass adapter position to another fragment on clicking the recycler view..

Fragment 1 code from recyclerview adapter:

holder.address.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Log.i("Position of items...///", String.valueOf(position));
                            //For sending data between fragments

                            Bundle bundle = new Bundle();
                            bundle.putInt("Position", position);
                            StoreDetails storeDetails = new StoreDetails();
                            storeDetails.setArguments(bundle);
                            getActivity().getSupportFragmentManager()
                                    .beginTransaction()
                                    .replace(R.id.content_frame, new StoreDetails())
                                    .commit();

                        }
                    });

Fragment 2 code:

Bundle b = getArguments();
    if(b != null)
    {
        b.getInt("Position");
    }
    else
    {
        Toast.makeText(getActivity(), "Oops sorry..!!", Toast.LENGTH_SHORT).show();
    }

Upvotes: 2

Views: 1615

Answers (2)

AskNilesh
AskNilesh

Reputation: 69689

you are adding Bundle in StoreDetails Fragment and your are passing new object of StoreDetails Fragment

you need to pass same object of your StoreDetails Fragment in which you add the Bundle so change this as below code

use this

Bundle bundle = new Bundle();
bundle.putInt("Position", position);
StoreDetails storeDetails = new StoreDetails();
storeDetails.setArguments(bundle);
getActivity().getSupportFragmentManager()
              .beginTransaction()
              .replace(R.id.content_frame,  storeDetails)
              .commit();

instead of this

getActivity().getSupportFragmentManager()
             .beginTransaction()
             .replace(R.id.content_frame,new StoreDetails())
             .commit();

Upvotes: 4

Karthik
Karthik

Reputation: 1219

Try like this:

    private Bundle bundle;

@Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
     super.onActivityCreated(savedInstanceState);
     this.bundle = getArguments();
     if (bundle != null) {
         bundle.getInt("Position");
     } else {
         Toast.makeText(getActivity(), "Oops sorry..!!", Toast.LENGTH_SHORT).show();
             }
    }

Upvotes: 0

Related Questions