Passing data from RecyclerView.Adapter to fragment onClickCallback to a Fragment from a DialogFragmentIs Java “pass-by-reference” or “pass-by-value”?Create ArrayList from arrayHow do I call one constructor from another in Java?How to get an enum value from a string value in Java?Stop EditText from gaining focus at Activity startupHow do I pass data between Activities in Android application?findViewById in FragmentRecyclerView onClickHow to add child(Product) under a child(Store) in Firebase Database using RecyclerView

What does it mean by "my days-of-the-week underwear only go to Thursday" in this context?

I transpose the source code, you transpose the input!

Is there a list of world wide upcoming space events on the web?

Pushing the e-pawn

"I will not" or "I don't" as an answer for negative orders?

After viewing logs with journalctl, how do I exit the screen that says "lines 1-2/2 (END)"?

How can I become an invalid target for spells that target humanoids?

Beyond Futuristic Technology for an Alien Warship?

I reverse the source code, you reverse the input!

How many stack cables would be needed if we want to stack two 3850 switches

How deep is the liquid in a half-full hemisphere?

Why aren't faces sharp in my f/1.8 portraits even though I'm carefully using center-point autofocus?

GPLv3 forces us to make code available, but to who?

Would an object shot from earth fall into the sun?

How do my husband and I get over our fear of having another difficult baby?

How to prevent pickpocketing in busy bars?

Why would an airline put 15 passengers at once on standby?

Can a passenger predict that an airline is about to go bankrupt?

How do we know neutrons have no charge?

Is the illusion created by Invoke Duplicity affected by difficult terrain?

A famous scholar sent me an unpublished draft of hers. Then she died. I think her work should be published. What should I do?

Format columns in output with awk

"until mine is on tight" is a idiom?

Windows 10 deletes lots of tiny files super slowly. Anything that can be done to speed it up?



Passing data from RecyclerView.Adapter to fragment onClick


Callback to a Fragment from a DialogFragmentIs Java “pass-by-reference” or “pass-by-value”?Create ArrayList from arrayHow do I call one constructor from another in Java?How to get an enum value from a string value in Java?Stop EditText from gaining focus at Activity startupHow do I pass data between Activities in Android application?findViewById in FragmentRecyclerView onClickHow to add child(Product) under a child(Store) in Firebase Database using RecyclerView






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















I'm trying to figure out how to get data from a clicked item in a RecyclerView to a listview in a Fragment. I can't seem to figure out how to do this, as I can't get my bundle to work.



I've tried various solutions offered here on Stackoverflow, but none of them have worked. I have managed to get the info from the recyclerview, but I am stuck trying to figure out how I can pass it to the fragment. Can someone please help me?



The Adapter class:



public class FoodAdapter extends RecyclerView.Adapter<FoodAdapter.ViewHolder> 

private Context context;

ArrayList<FoodActivity> list;
public FoodAdapter(ArrayList<FoodActivity> list)
this.list = list;



@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType)
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.listview_item_food, parent, false);

return new ViewHolder(view);


@Override
public void onBindViewHolder(@NonNull final ViewHolder holder, final int position)
holder.foods.setText(list.get(position).getName());
holder.carbo.setText(list.get(position).getCarbohydrates());
holder.protein.setText(list.get(position).getProtein());
holder.fats.setText(list.get(position).getFats());

//Get items from recyclerview when user clicks them. Then send them to FoodFragment
holder.itemView.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View v)

String foods = list.get(position).getName();
String carbo = list.get(position).getCarbohydrates();
String protein = list.get(position).getProtein();
String fats = list.get(position).getFats();

Toast.makeText(v.getContext(), "test: " + foods, Toast.LENGTH_SHORT).show();



);



@Override
public int getItemCount()
return list.size();


class ViewHolder extends RecyclerView.ViewHolder
TextView foods, carbo, fats, protein;

public ViewHolder(View itemView)
super(itemView);

carbo = itemView.findViewById(R.id.carbo);
protein = itemView.findViewById(R.id.protein);
fats = itemView.findViewById(R.id.fats);
foods = itemView.findViewById(R.id.food);





The Fragment where the data comes from:



public class TrackingFragment extends Fragment 

DatabaseReference databaseReference;
ArrayList<FoodActivity> list;
RecyclerView recyclerView;
SearchView searchView;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState)
View view = inflater.inflate(R.layout.fragment_tracking, container, false);

databaseReference = FirebaseDatabase.getInstance().getReference().child("foods");
recyclerView = view.findViewById(R.id.rv);
searchView = view.findViewById(R.id.searchFood);

return view;


@Override
public void onStart()
super.onStart();

if(databaseReference != null)
databaseReference.addValueEventListener(new ValueEventListener()
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot)
if(dataSnapshot.exists())
list = new ArrayList<>();
for(DataSnapshot ds : dataSnapshot.getChildren())
list.add(ds.getValue(FoodActivity.class));

FoodAdapter adapter = new FoodAdapter(list);
recyclerView.setAdapter(adapter);





@Override
public void onCancelled(@NonNull DatabaseError databaseError)
Toast.makeText(getActivity(), databaseError.getMessage(), Toast.LENGTH_SHORT).show();

);

if(searchView != null)
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener()
@Override
public boolean onQueryTextSubmit(String query)
return false;


@Override
public boolean onQueryTextChange(String newText)
search(newText);
return true;

);



private void search(String str)
ArrayList<FoodActivity> searchList = new ArrayList<>();
for(FoodActivity object : list)
if(object.getName().toLowerCase().contains(str.toLowerCase()))
searchList.add(object);


FoodAdapter foodAdapter = new FoodAdapter(searchList);
recyclerView.setAdapter(foodAdapter);





And the class where it needs to go:



public class FoodFragment extends Fragment 

ImageButton addFood;

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

addFood = view.findViewById(R.id.addFood);

addFood.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View v)

FragmentTransaction fr = getFragmentManager().beginTransaction();
fr.replace(R.id.fragment_container, new TrackingFragment());
fr.addToBackStack(null).commit();

);

return view;












share|improve this question
























  • Base on this code it's hard to say where are you using FoodFragment. Are both fragments are in the same Activity? Have you got TrackingFragment with FoodAdapter, right?

    – Boken
    Mar 28 at 19:28











  • I'm not entirely sure what you mean. FoodFragment is called from a MenuActivity with a bottomNavigationView, and then TrackingFragment is called from the FoodFragment. FoodAdapter is connected to TrackingFrackment yes.

    – Flex
    Mar 28 at 19:40











  • But how exactly is you layout designed? You have a MenuActivity, which displays the FoodFragment, and when you select something, you replace you food Fragment with the TrackingFragment, or do you open a new Activity, which displays the Tracking fragment?

    – glm9637
    Mar 28 at 20:14











  • In the MenuActivity I have a fragment_container in a FrameLayout. I simply replace the fragments in that container whenever I have to display a new fragment.

    – Flex
    Mar 28 at 20:29

















0















I'm trying to figure out how to get data from a clicked item in a RecyclerView to a listview in a Fragment. I can't seem to figure out how to do this, as I can't get my bundle to work.



I've tried various solutions offered here on Stackoverflow, but none of them have worked. I have managed to get the info from the recyclerview, but I am stuck trying to figure out how I can pass it to the fragment. Can someone please help me?



The Adapter class:



public class FoodAdapter extends RecyclerView.Adapter<FoodAdapter.ViewHolder> 

private Context context;

ArrayList<FoodActivity> list;
public FoodAdapter(ArrayList<FoodActivity> list)
this.list = list;



@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType)
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.listview_item_food, parent, false);

return new ViewHolder(view);


@Override
public void onBindViewHolder(@NonNull final ViewHolder holder, final int position)
holder.foods.setText(list.get(position).getName());
holder.carbo.setText(list.get(position).getCarbohydrates());
holder.protein.setText(list.get(position).getProtein());
holder.fats.setText(list.get(position).getFats());

//Get items from recyclerview when user clicks them. Then send them to FoodFragment
holder.itemView.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View v)

String foods = list.get(position).getName();
String carbo = list.get(position).getCarbohydrates();
String protein = list.get(position).getProtein();
String fats = list.get(position).getFats();

Toast.makeText(v.getContext(), "test: " + foods, Toast.LENGTH_SHORT).show();



);



@Override
public int getItemCount()
return list.size();


class ViewHolder extends RecyclerView.ViewHolder
TextView foods, carbo, fats, protein;

public ViewHolder(View itemView)
super(itemView);

carbo = itemView.findViewById(R.id.carbo);
protein = itemView.findViewById(R.id.protein);
fats = itemView.findViewById(R.id.fats);
foods = itemView.findViewById(R.id.food);





The Fragment where the data comes from:



public class TrackingFragment extends Fragment 

DatabaseReference databaseReference;
ArrayList<FoodActivity> list;
RecyclerView recyclerView;
SearchView searchView;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState)
View view = inflater.inflate(R.layout.fragment_tracking, container, false);

databaseReference = FirebaseDatabase.getInstance().getReference().child("foods");
recyclerView = view.findViewById(R.id.rv);
searchView = view.findViewById(R.id.searchFood);

return view;


@Override
public void onStart()
super.onStart();

if(databaseReference != null)
databaseReference.addValueEventListener(new ValueEventListener()
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot)
if(dataSnapshot.exists())
list = new ArrayList<>();
for(DataSnapshot ds : dataSnapshot.getChildren())
list.add(ds.getValue(FoodActivity.class));

FoodAdapter adapter = new FoodAdapter(list);
recyclerView.setAdapter(adapter);





@Override
public void onCancelled(@NonNull DatabaseError databaseError)
Toast.makeText(getActivity(), databaseError.getMessage(), Toast.LENGTH_SHORT).show();

);

if(searchView != null)
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener()
@Override
public boolean onQueryTextSubmit(String query)
return false;


@Override
public boolean onQueryTextChange(String newText)
search(newText);
return true;

);



private void search(String str)
ArrayList<FoodActivity> searchList = new ArrayList<>();
for(FoodActivity object : list)
if(object.getName().toLowerCase().contains(str.toLowerCase()))
searchList.add(object);


FoodAdapter foodAdapter = new FoodAdapter(searchList);
recyclerView.setAdapter(foodAdapter);





And the class where it needs to go:



public class FoodFragment extends Fragment 

ImageButton addFood;

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

addFood = view.findViewById(R.id.addFood);

addFood.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View v)

FragmentTransaction fr = getFragmentManager().beginTransaction();
fr.replace(R.id.fragment_container, new TrackingFragment());
fr.addToBackStack(null).commit();

);

return view;












share|improve this question
























  • Base on this code it's hard to say where are you using FoodFragment. Are both fragments are in the same Activity? Have you got TrackingFragment with FoodAdapter, right?

    – Boken
    Mar 28 at 19:28











  • I'm not entirely sure what you mean. FoodFragment is called from a MenuActivity with a bottomNavigationView, and then TrackingFragment is called from the FoodFragment. FoodAdapter is connected to TrackingFrackment yes.

    – Flex
    Mar 28 at 19:40











  • But how exactly is you layout designed? You have a MenuActivity, which displays the FoodFragment, and when you select something, you replace you food Fragment with the TrackingFragment, or do you open a new Activity, which displays the Tracking fragment?

    – glm9637
    Mar 28 at 20:14











  • In the MenuActivity I have a fragment_container in a FrameLayout. I simply replace the fragments in that container whenever I have to display a new fragment.

    – Flex
    Mar 28 at 20:29













0












0








0








I'm trying to figure out how to get data from a clicked item in a RecyclerView to a listview in a Fragment. I can't seem to figure out how to do this, as I can't get my bundle to work.



I've tried various solutions offered here on Stackoverflow, but none of them have worked. I have managed to get the info from the recyclerview, but I am stuck trying to figure out how I can pass it to the fragment. Can someone please help me?



The Adapter class:



public class FoodAdapter extends RecyclerView.Adapter<FoodAdapter.ViewHolder> 

private Context context;

ArrayList<FoodActivity> list;
public FoodAdapter(ArrayList<FoodActivity> list)
this.list = list;



@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType)
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.listview_item_food, parent, false);

return new ViewHolder(view);


@Override
public void onBindViewHolder(@NonNull final ViewHolder holder, final int position)
holder.foods.setText(list.get(position).getName());
holder.carbo.setText(list.get(position).getCarbohydrates());
holder.protein.setText(list.get(position).getProtein());
holder.fats.setText(list.get(position).getFats());

//Get items from recyclerview when user clicks them. Then send them to FoodFragment
holder.itemView.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View v)

String foods = list.get(position).getName();
String carbo = list.get(position).getCarbohydrates();
String protein = list.get(position).getProtein();
String fats = list.get(position).getFats();

Toast.makeText(v.getContext(), "test: " + foods, Toast.LENGTH_SHORT).show();



);



@Override
public int getItemCount()
return list.size();


class ViewHolder extends RecyclerView.ViewHolder
TextView foods, carbo, fats, protein;

public ViewHolder(View itemView)
super(itemView);

carbo = itemView.findViewById(R.id.carbo);
protein = itemView.findViewById(R.id.protein);
fats = itemView.findViewById(R.id.fats);
foods = itemView.findViewById(R.id.food);





The Fragment where the data comes from:



public class TrackingFragment extends Fragment 

DatabaseReference databaseReference;
ArrayList<FoodActivity> list;
RecyclerView recyclerView;
SearchView searchView;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState)
View view = inflater.inflate(R.layout.fragment_tracking, container, false);

databaseReference = FirebaseDatabase.getInstance().getReference().child("foods");
recyclerView = view.findViewById(R.id.rv);
searchView = view.findViewById(R.id.searchFood);

return view;


@Override
public void onStart()
super.onStart();

if(databaseReference != null)
databaseReference.addValueEventListener(new ValueEventListener()
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot)
if(dataSnapshot.exists())
list = new ArrayList<>();
for(DataSnapshot ds : dataSnapshot.getChildren())
list.add(ds.getValue(FoodActivity.class));

FoodAdapter adapter = new FoodAdapter(list);
recyclerView.setAdapter(adapter);





@Override
public void onCancelled(@NonNull DatabaseError databaseError)
Toast.makeText(getActivity(), databaseError.getMessage(), Toast.LENGTH_SHORT).show();

);

if(searchView != null)
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener()
@Override
public boolean onQueryTextSubmit(String query)
return false;


@Override
public boolean onQueryTextChange(String newText)
search(newText);
return true;

);



private void search(String str)
ArrayList<FoodActivity> searchList = new ArrayList<>();
for(FoodActivity object : list)
if(object.getName().toLowerCase().contains(str.toLowerCase()))
searchList.add(object);


FoodAdapter foodAdapter = new FoodAdapter(searchList);
recyclerView.setAdapter(foodAdapter);





And the class where it needs to go:



public class FoodFragment extends Fragment 

ImageButton addFood;

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

addFood = view.findViewById(R.id.addFood);

addFood.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View v)

FragmentTransaction fr = getFragmentManager().beginTransaction();
fr.replace(R.id.fragment_container, new TrackingFragment());
fr.addToBackStack(null).commit();

);

return view;












share|improve this question














I'm trying to figure out how to get data from a clicked item in a RecyclerView to a listview in a Fragment. I can't seem to figure out how to do this, as I can't get my bundle to work.



I've tried various solutions offered here on Stackoverflow, but none of them have worked. I have managed to get the info from the recyclerview, but I am stuck trying to figure out how I can pass it to the fragment. Can someone please help me?



The Adapter class:



public class FoodAdapter extends RecyclerView.Adapter<FoodAdapter.ViewHolder> 

private Context context;

ArrayList<FoodActivity> list;
public FoodAdapter(ArrayList<FoodActivity> list)
this.list = list;



@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType)
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.listview_item_food, parent, false);

return new ViewHolder(view);


@Override
public void onBindViewHolder(@NonNull final ViewHolder holder, final int position)
holder.foods.setText(list.get(position).getName());
holder.carbo.setText(list.get(position).getCarbohydrates());
holder.protein.setText(list.get(position).getProtein());
holder.fats.setText(list.get(position).getFats());

//Get items from recyclerview when user clicks them. Then send them to FoodFragment
holder.itemView.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View v)

String foods = list.get(position).getName();
String carbo = list.get(position).getCarbohydrates();
String protein = list.get(position).getProtein();
String fats = list.get(position).getFats();

Toast.makeText(v.getContext(), "test: " + foods, Toast.LENGTH_SHORT).show();



);



@Override
public int getItemCount()
return list.size();


class ViewHolder extends RecyclerView.ViewHolder
TextView foods, carbo, fats, protein;

public ViewHolder(View itemView)
super(itemView);

carbo = itemView.findViewById(R.id.carbo);
protein = itemView.findViewById(R.id.protein);
fats = itemView.findViewById(R.id.fats);
foods = itemView.findViewById(R.id.food);





The Fragment where the data comes from:



public class TrackingFragment extends Fragment 

DatabaseReference databaseReference;
ArrayList<FoodActivity> list;
RecyclerView recyclerView;
SearchView searchView;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState)
View view = inflater.inflate(R.layout.fragment_tracking, container, false);

databaseReference = FirebaseDatabase.getInstance().getReference().child("foods");
recyclerView = view.findViewById(R.id.rv);
searchView = view.findViewById(R.id.searchFood);

return view;


@Override
public void onStart()
super.onStart();

if(databaseReference != null)
databaseReference.addValueEventListener(new ValueEventListener()
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot)
if(dataSnapshot.exists())
list = new ArrayList<>();
for(DataSnapshot ds : dataSnapshot.getChildren())
list.add(ds.getValue(FoodActivity.class));

FoodAdapter adapter = new FoodAdapter(list);
recyclerView.setAdapter(adapter);





@Override
public void onCancelled(@NonNull DatabaseError databaseError)
Toast.makeText(getActivity(), databaseError.getMessage(), Toast.LENGTH_SHORT).show();

);

if(searchView != null)
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener()
@Override
public boolean onQueryTextSubmit(String query)
return false;


@Override
public boolean onQueryTextChange(String newText)
search(newText);
return true;

);



private void search(String str)
ArrayList<FoodActivity> searchList = new ArrayList<>();
for(FoodActivity object : list)
if(object.getName().toLowerCase().contains(str.toLowerCase()))
searchList.add(object);


FoodAdapter foodAdapter = new FoodAdapter(searchList);
recyclerView.setAdapter(foodAdapter);





And the class where it needs to go:



public class FoodFragment extends Fragment 

ImageButton addFood;

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

addFood = view.findViewById(R.id.addFood);

addFood.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View v)

FragmentTransaction fr = getFragmentManager().beginTransaction();
fr.replace(R.id.fragment_container, new TrackingFragment());
fr.addToBackStack(null).commit();

);

return view;









java android android-recyclerview fragment adapter






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 28 at 19:16









FlexFlex

137 bronze badges




137 bronze badges















  • Base on this code it's hard to say where are you using FoodFragment. Are both fragments are in the same Activity? Have you got TrackingFragment with FoodAdapter, right?

    – Boken
    Mar 28 at 19:28











  • I'm not entirely sure what you mean. FoodFragment is called from a MenuActivity with a bottomNavigationView, and then TrackingFragment is called from the FoodFragment. FoodAdapter is connected to TrackingFrackment yes.

    – Flex
    Mar 28 at 19:40











  • But how exactly is you layout designed? You have a MenuActivity, which displays the FoodFragment, and when you select something, you replace you food Fragment with the TrackingFragment, or do you open a new Activity, which displays the Tracking fragment?

    – glm9637
    Mar 28 at 20:14











  • In the MenuActivity I have a fragment_container in a FrameLayout. I simply replace the fragments in that container whenever I have to display a new fragment.

    – Flex
    Mar 28 at 20:29

















  • Base on this code it's hard to say where are you using FoodFragment. Are both fragments are in the same Activity? Have you got TrackingFragment with FoodAdapter, right?

    – Boken
    Mar 28 at 19:28











  • I'm not entirely sure what you mean. FoodFragment is called from a MenuActivity with a bottomNavigationView, and then TrackingFragment is called from the FoodFragment. FoodAdapter is connected to TrackingFrackment yes.

    – Flex
    Mar 28 at 19:40











  • But how exactly is you layout designed? You have a MenuActivity, which displays the FoodFragment, and when you select something, you replace you food Fragment with the TrackingFragment, or do you open a new Activity, which displays the Tracking fragment?

    – glm9637
    Mar 28 at 20:14











  • In the MenuActivity I have a fragment_container in a FrameLayout. I simply replace the fragments in that container whenever I have to display a new fragment.

    – Flex
    Mar 28 at 20:29
















Base on this code it's hard to say where are you using FoodFragment. Are both fragments are in the same Activity? Have you got TrackingFragment with FoodAdapter, right?

– Boken
Mar 28 at 19:28





Base on this code it's hard to say where are you using FoodFragment. Are both fragments are in the same Activity? Have you got TrackingFragment with FoodAdapter, right?

– Boken
Mar 28 at 19:28













I'm not entirely sure what you mean. FoodFragment is called from a MenuActivity with a bottomNavigationView, and then TrackingFragment is called from the FoodFragment. FoodAdapter is connected to TrackingFrackment yes.

– Flex
Mar 28 at 19:40





I'm not entirely sure what you mean. FoodFragment is called from a MenuActivity with a bottomNavigationView, and then TrackingFragment is called from the FoodFragment. FoodAdapter is connected to TrackingFrackment yes.

– Flex
Mar 28 at 19:40













But how exactly is you layout designed? You have a MenuActivity, which displays the FoodFragment, and when you select something, you replace you food Fragment with the TrackingFragment, or do you open a new Activity, which displays the Tracking fragment?

– glm9637
Mar 28 at 20:14





But how exactly is you layout designed? You have a MenuActivity, which displays the FoodFragment, and when you select something, you replace you food Fragment with the TrackingFragment, or do you open a new Activity, which displays the Tracking fragment?

– glm9637
Mar 28 at 20:14













In the MenuActivity I have a fragment_container in a FrameLayout. I simply replace the fragments in that container whenever I have to display a new fragment.

– Flex
Mar 28 at 20:29





In the MenuActivity I have a fragment_container in a FrameLayout. I simply replace the fragments in that container whenever I have to display a new fragment.

– Flex
Mar 28 at 20:29












3 Answers
3






active

oldest

votes


















0
















To get your data from FoodAdapter to TrackingFragment, you can add TrackingFragment (or an interface it implements, ideally) as a parameter to the FoodAdapter constructor, then use that instance to forward your ViewHolder clicks to TrackingFragment for handling.



To get your data from TrackingFragment to FoodFragment, use the setTargetFragment/onActivityResult pattern for fragment <-> fragment communication. This answer has an example: https://stackoverflow.com/a/13733914/3238938






share|improve this answer
































    0
















    The most simple is to add variables you need to your activity, set their values with onClick() and then retrieve data in other fragment:




    • in activity:



      String foods;

      public String getFoods()
      return foods;


      public void setFoods(String foods)
      this.foods = foods;




    • in adapter:



       holder.itemView.setOnClickListener(new View.OnClickListener() 
      @Override
      public void onClick(View v)
      ((YourActivity)getActivity()).setFoods("Any value");

      );



    • in destination fragment:



      String foods = ((YourActivity)getActivity()).getFoods();







    share|improve this answer
































      0
















      Add an interface to your adapter as follow



      public class FoodAdapter extends RecyclerView.Adapter<FoodAdapter.ViewHolder> 

      interface OnClickListener
      void onClick(FoodActivity clickedItem);


      private OnClickListener mCallback;
      private ArrayList<FoodActivity> list;

      public FoodAdapter(ArrayList<FoodActivity> list)
      this.list = list;


      public void setOnClickListener(OnClickListener callback)
      mCallback = callback;



      @NonNull
      @Override
      public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType)
      View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.listview_item_food, parent, false);

      return new ViewHolder(view);


      @Override
      public void onBindViewHolder(@NonNull final ViewHolder holder, final int position)
      holder.foods.setText(list.get(position).getName());
      holder.carbo.setText(list.get(position).getCarbohydrates());
      holder.protein.setText(list.get(position).getProtein());
      holder.fats.setText(list.get(position).getFats());

      //Get items from recyclerview when user clicks them. Then send them to FoodFragment
      holder.itemView.setOnClickListener(new View.OnClickListener()
      @Override
      public void onClick(View v)
      if (mCallback != null)
      mCallback.onClick(list.get(position));

      );



      @Override
      public int getItemCount()
      return list.size();


      class ViewHolder extends RecyclerView.ViewHolder
      TextView foods, carbo, fats, protein;

      public ViewHolder(View itemView)
      super(itemView);

      carbo = itemView.findViewById(R.id.carbo);
      protein = itemView.findViewById(R.id.protein);
      fats = itemView.findViewById(R.id.fats);
      foods = itemView.findViewById(R.id.food);








      share|improve this answer

























      • Thank you for taking your time to answer. I've tried getting the data in the FoodFragment, but can't seem to get it to work (I haven't worked with interfaces before and the things I've tried hasn't worked). Would you mind showing me how to retrieve that data also?

        – Flex
        Mar 29 at 9:50













      Your Answer






      StackExchange.ifUsing("editor", function ()
      StackExchange.using("externalEditor", function ()
      StackExchange.using("snippets", function ()
      StackExchange.snippets.init();
      );
      );
      , "code-snippets");

      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "1"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/4.0/"u003ecc by-sa 4.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );














      draft saved

      draft discarded
















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55405312%2fpassing-data-from-recyclerview-adapter-to-fragment-onclick%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      3 Answers
      3






      active

      oldest

      votes








      3 Answers
      3






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      0
















      To get your data from FoodAdapter to TrackingFragment, you can add TrackingFragment (or an interface it implements, ideally) as a parameter to the FoodAdapter constructor, then use that instance to forward your ViewHolder clicks to TrackingFragment for handling.



      To get your data from TrackingFragment to FoodFragment, use the setTargetFragment/onActivityResult pattern for fragment <-> fragment communication. This answer has an example: https://stackoverflow.com/a/13733914/3238938






      share|improve this answer





























        0
















        To get your data from FoodAdapter to TrackingFragment, you can add TrackingFragment (or an interface it implements, ideally) as a parameter to the FoodAdapter constructor, then use that instance to forward your ViewHolder clicks to TrackingFragment for handling.



        To get your data from TrackingFragment to FoodFragment, use the setTargetFragment/onActivityResult pattern for fragment <-> fragment communication. This answer has an example: https://stackoverflow.com/a/13733914/3238938






        share|improve this answer



























          0














          0










          0









          To get your data from FoodAdapter to TrackingFragment, you can add TrackingFragment (or an interface it implements, ideally) as a parameter to the FoodAdapter constructor, then use that instance to forward your ViewHolder clicks to TrackingFragment for handling.



          To get your data from TrackingFragment to FoodFragment, use the setTargetFragment/onActivityResult pattern for fragment <-> fragment communication. This answer has an example: https://stackoverflow.com/a/13733914/3238938






          share|improve this answer













          To get your data from FoodAdapter to TrackingFragment, you can add TrackingFragment (or an interface it implements, ideally) as a parameter to the FoodAdapter constructor, then use that instance to forward your ViewHolder clicks to TrackingFragment for handling.



          To get your data from TrackingFragment to FoodFragment, use the setTargetFragment/onActivityResult pattern for fragment <-> fragment communication. This answer has an example: https://stackoverflow.com/a/13733914/3238938







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Mar 28 at 20:20









          Damien DiehlDamien Diehl

          3214 silver badges12 bronze badges




          3214 silver badges12 bronze badges


























              0
















              The most simple is to add variables you need to your activity, set their values with onClick() and then retrieve data in other fragment:




              • in activity:



                String foods;

                public String getFoods()
                return foods;


                public void setFoods(String foods)
                this.foods = foods;




              • in adapter:



                 holder.itemView.setOnClickListener(new View.OnClickListener() 
                @Override
                public void onClick(View v)
                ((YourActivity)getActivity()).setFoods("Any value");

                );



              • in destination fragment:



                String foods = ((YourActivity)getActivity()).getFoods();







              share|improve this answer





























                0
















                The most simple is to add variables you need to your activity, set their values with onClick() and then retrieve data in other fragment:




                • in activity:



                  String foods;

                  public String getFoods()
                  return foods;


                  public void setFoods(String foods)
                  this.foods = foods;




                • in adapter:



                   holder.itemView.setOnClickListener(new View.OnClickListener() 
                  @Override
                  public void onClick(View v)
                  ((YourActivity)getActivity()).setFoods("Any value");

                  );



                • in destination fragment:



                  String foods = ((YourActivity)getActivity()).getFoods();







                share|improve this answer



























                  0














                  0










                  0









                  The most simple is to add variables you need to your activity, set their values with onClick() and then retrieve data in other fragment:




                  • in activity:



                    String foods;

                    public String getFoods()
                    return foods;


                    public void setFoods(String foods)
                    this.foods = foods;




                  • in adapter:



                     holder.itemView.setOnClickListener(new View.OnClickListener() 
                    @Override
                    public void onClick(View v)
                    ((YourActivity)getActivity()).setFoods("Any value");

                    );



                  • in destination fragment:



                    String foods = ((YourActivity)getActivity()).getFoods();







                  share|improve this answer













                  The most simple is to add variables you need to your activity, set their values with onClick() and then retrieve data in other fragment:




                  • in activity:



                    String foods;

                    public String getFoods()
                    return foods;


                    public void setFoods(String foods)
                    this.foods = foods;




                  • in adapter:



                     holder.itemView.setOnClickListener(new View.OnClickListener() 
                    @Override
                    public void onClick(View v)
                    ((YourActivity)getActivity()).setFoods("Any value");

                    );



                  • in destination fragment:



                    String foods = ((YourActivity)getActivity()).getFoods();








                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Mar 28 at 20:25









                  Alexander GapanowichAlexander Gapanowich

                  3946 bronze badges




                  3946 bronze badges
























                      0
















                      Add an interface to your adapter as follow



                      public class FoodAdapter extends RecyclerView.Adapter<FoodAdapter.ViewHolder> 

                      interface OnClickListener
                      void onClick(FoodActivity clickedItem);


                      private OnClickListener mCallback;
                      private ArrayList<FoodActivity> list;

                      public FoodAdapter(ArrayList<FoodActivity> list)
                      this.list = list;


                      public void setOnClickListener(OnClickListener callback)
                      mCallback = callback;



                      @NonNull
                      @Override
                      public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType)
                      View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.listview_item_food, parent, false);

                      return new ViewHolder(view);


                      @Override
                      public void onBindViewHolder(@NonNull final ViewHolder holder, final int position)
                      holder.foods.setText(list.get(position).getName());
                      holder.carbo.setText(list.get(position).getCarbohydrates());
                      holder.protein.setText(list.get(position).getProtein());
                      holder.fats.setText(list.get(position).getFats());

                      //Get items from recyclerview when user clicks them. Then send them to FoodFragment
                      holder.itemView.setOnClickListener(new View.OnClickListener()
                      @Override
                      public void onClick(View v)
                      if (mCallback != null)
                      mCallback.onClick(list.get(position));

                      );



                      @Override
                      public int getItemCount()
                      return list.size();


                      class ViewHolder extends RecyclerView.ViewHolder
                      TextView foods, carbo, fats, protein;

                      public ViewHolder(View itemView)
                      super(itemView);

                      carbo = itemView.findViewById(R.id.carbo);
                      protein = itemView.findViewById(R.id.protein);
                      fats = itemView.findViewById(R.id.fats);
                      foods = itemView.findViewById(R.id.food);








                      share|improve this answer

























                      • Thank you for taking your time to answer. I've tried getting the data in the FoodFragment, but can't seem to get it to work (I haven't worked with interfaces before and the things I've tried hasn't worked). Would you mind showing me how to retrieve that data also?

                        – Flex
                        Mar 29 at 9:50















                      0
















                      Add an interface to your adapter as follow



                      public class FoodAdapter extends RecyclerView.Adapter<FoodAdapter.ViewHolder> 

                      interface OnClickListener
                      void onClick(FoodActivity clickedItem);


                      private OnClickListener mCallback;
                      private ArrayList<FoodActivity> list;

                      public FoodAdapter(ArrayList<FoodActivity> list)
                      this.list = list;


                      public void setOnClickListener(OnClickListener callback)
                      mCallback = callback;



                      @NonNull
                      @Override
                      public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType)
                      View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.listview_item_food, parent, false);

                      return new ViewHolder(view);


                      @Override
                      public void onBindViewHolder(@NonNull final ViewHolder holder, final int position)
                      holder.foods.setText(list.get(position).getName());
                      holder.carbo.setText(list.get(position).getCarbohydrates());
                      holder.protein.setText(list.get(position).getProtein());
                      holder.fats.setText(list.get(position).getFats());

                      //Get items from recyclerview when user clicks them. Then send them to FoodFragment
                      holder.itemView.setOnClickListener(new View.OnClickListener()
                      @Override
                      public void onClick(View v)
                      if (mCallback != null)
                      mCallback.onClick(list.get(position));

                      );



                      @Override
                      public int getItemCount()
                      return list.size();


                      class ViewHolder extends RecyclerView.ViewHolder
                      TextView foods, carbo, fats, protein;

                      public ViewHolder(View itemView)
                      super(itemView);

                      carbo = itemView.findViewById(R.id.carbo);
                      protein = itemView.findViewById(R.id.protein);
                      fats = itemView.findViewById(R.id.fats);
                      foods = itemView.findViewById(R.id.food);








                      share|improve this answer

























                      • Thank you for taking your time to answer. I've tried getting the data in the FoodFragment, but can't seem to get it to work (I haven't worked with interfaces before and the things I've tried hasn't worked). Would you mind showing me how to retrieve that data also?

                        – Flex
                        Mar 29 at 9:50













                      0














                      0










                      0









                      Add an interface to your adapter as follow



                      public class FoodAdapter extends RecyclerView.Adapter<FoodAdapter.ViewHolder> 

                      interface OnClickListener
                      void onClick(FoodActivity clickedItem);


                      private OnClickListener mCallback;
                      private ArrayList<FoodActivity> list;

                      public FoodAdapter(ArrayList<FoodActivity> list)
                      this.list = list;


                      public void setOnClickListener(OnClickListener callback)
                      mCallback = callback;



                      @NonNull
                      @Override
                      public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType)
                      View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.listview_item_food, parent, false);

                      return new ViewHolder(view);


                      @Override
                      public void onBindViewHolder(@NonNull final ViewHolder holder, final int position)
                      holder.foods.setText(list.get(position).getName());
                      holder.carbo.setText(list.get(position).getCarbohydrates());
                      holder.protein.setText(list.get(position).getProtein());
                      holder.fats.setText(list.get(position).getFats());

                      //Get items from recyclerview when user clicks them. Then send them to FoodFragment
                      holder.itemView.setOnClickListener(new View.OnClickListener()
                      @Override
                      public void onClick(View v)
                      if (mCallback != null)
                      mCallback.onClick(list.get(position));

                      );



                      @Override
                      public int getItemCount()
                      return list.size();


                      class ViewHolder extends RecyclerView.ViewHolder
                      TextView foods, carbo, fats, protein;

                      public ViewHolder(View itemView)
                      super(itemView);

                      carbo = itemView.findViewById(R.id.carbo);
                      protein = itemView.findViewById(R.id.protein);
                      fats = itemView.findViewById(R.id.fats);
                      foods = itemView.findViewById(R.id.food);








                      share|improve this answer













                      Add an interface to your adapter as follow



                      public class FoodAdapter extends RecyclerView.Adapter<FoodAdapter.ViewHolder> 

                      interface OnClickListener
                      void onClick(FoodActivity clickedItem);


                      private OnClickListener mCallback;
                      private ArrayList<FoodActivity> list;

                      public FoodAdapter(ArrayList<FoodActivity> list)
                      this.list = list;


                      public void setOnClickListener(OnClickListener callback)
                      mCallback = callback;



                      @NonNull
                      @Override
                      public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType)
                      View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.listview_item_food, parent, false);

                      return new ViewHolder(view);


                      @Override
                      public void onBindViewHolder(@NonNull final ViewHolder holder, final int position)
                      holder.foods.setText(list.get(position).getName());
                      holder.carbo.setText(list.get(position).getCarbohydrates());
                      holder.protein.setText(list.get(position).getProtein());
                      holder.fats.setText(list.get(position).getFats());

                      //Get items from recyclerview when user clicks them. Then send them to FoodFragment
                      holder.itemView.setOnClickListener(new View.OnClickListener()
                      @Override
                      public void onClick(View v)
                      if (mCallback != null)
                      mCallback.onClick(list.get(position));

                      );



                      @Override
                      public int getItemCount()
                      return list.size();


                      class ViewHolder extends RecyclerView.ViewHolder
                      TextView foods, carbo, fats, protein;

                      public ViewHolder(View itemView)
                      super(itemView);

                      carbo = itemView.findViewById(R.id.carbo);
                      protein = itemView.findViewById(R.id.protein);
                      fats = itemView.findViewById(R.id.fats);
                      foods = itemView.findViewById(R.id.food);









                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Mar 28 at 20:33









                      Juan HurtadoJuan Hurtado

                      1817 bronze badges




                      1817 bronze badges















                      • Thank you for taking your time to answer. I've tried getting the data in the FoodFragment, but can't seem to get it to work (I haven't worked with interfaces before and the things I've tried hasn't worked). Would you mind showing me how to retrieve that data also?

                        – Flex
                        Mar 29 at 9:50

















                      • Thank you for taking your time to answer. I've tried getting the data in the FoodFragment, but can't seem to get it to work (I haven't worked with interfaces before and the things I've tried hasn't worked). Would you mind showing me how to retrieve that data also?

                        – Flex
                        Mar 29 at 9:50
















                      Thank you for taking your time to answer. I've tried getting the data in the FoodFragment, but can't seem to get it to work (I haven't worked with interfaces before and the things I've tried hasn't worked). Would you mind showing me how to retrieve that data also?

                      – Flex
                      Mar 29 at 9:50





                      Thank you for taking your time to answer. I've tried getting the data in the FoodFragment, but can't seem to get it to work (I haven't worked with interfaces before and the things I've tried hasn't worked). Would you mind showing me how to retrieve that data also?

                      – Flex
                      Mar 29 at 9:50


















                      draft saved

                      draft discarded















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid


                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.

                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55405312%2fpassing-data-from-recyclerview-adapter-to-fragment-onclick%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                      Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

                      Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript