0

How to pass data from RecyclerView of fragment to another fragment.i getting error. when I start the app, the app crash within 5 seconds with the message
My RecyclerView of fragment..

 @Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
    final Categories categories = categoriesList.get(position);
    holder.name.setText((categories.getName()));
    Glide.with(context).load(categories.getThumbnail()).into(holder.thumbnail);
    holder.name.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
           String catId= String.valueOf(categories.getId());
            Toast.makeText(context,catId,Toast.LENGTH_SHORT).show();
            AppCompatActivity activity = (AppCompatActivity) view.getContext();
            AudioFragment myFragment = new AudioFragment();
            Bundle bundle=new Bundle();
            bundle.putString("name", catId); //key and value
            myFragment.setArguments(bundle);
            activity.getSupportFragmentManager().beginTransaction().replace(R.id.frag_container, myFragment).addToBackStack(null).commit();

        }
    });
}

New Fragment

public class AudioFragment extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment

   String CAT_ID = getArguments().getString("name");
    Toast.makeText(getContext(),CAT_ID,Toast.LENGTH_SHORT).show();

    return inflater.inflate(R.layout.fragment_audio, container, false);
}


}
Sanjeev Pal
  • 107
  • 1
  • 7

1 Answers1

0

You can do that by creating a static method to get instance of fragment along with some argument as following.

In your fragment.

public class AudioFragment extends Fragment {

    public static AudioFragment getInstance(String catId){
        AudioFragment myFragment = new AudioFragment();
        Bundle bundle=new Bundle();
        bundle.putString("name", catId); //key and value
        myFragment.setArguments(bundle);
        return myFragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        String CAT_ID = getArguments().getString("name");
        Toast.makeText(getContext(),CAT_ID,Toast.LENGTH_SHORT).show();

        return inflater.inflate(R.layout.fragment_value, container, false);
    }
} 

And in your activity class.

getSupportFragmentManager().beginTransaction().replace(R.id.container, AudioFragment.getInstance("12")).addToBackStack(null).commit();
Mayur Gajra
  • 2,009
  • 2
  • 8
  • 18