I have a recycler view that is being populated by firebase database. On the item.xml I have a button alongside data. On clicking the button on each item, I want to save supplier name in my database. Get error: nullpointer exception as my class Suppliers remains null. What is causing it?
Code
public class recyclerAdapter extends RecyclerView.Adapter<recyclerAdapter.MyViewHolder> {
Context context;
ArrayList<supplierClass> list;
public recyclerAdapter(Context context, ArrayList<supplierClass> list) {
this.context = context;
this.list = list;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.item,parent,false);
return new MyViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
supplierClass sc = list.get(position);
holder.sName.setText(sc.getsName());
holder.materialName.setText(sc.getMaterialName());
holder.CATEGORY.setText(sc.getCATEGORY());
}
#Override
public int getItemCount() {
return list.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder{
TextView sName,materialName,CATEGORY;
Button btnSelect;
DatabaseReference ref;
FirebaseUser user= FirebaseAuth.getInstance().getCurrentUser();
public MyViewHolder(#NonNull View itemView) {
super(itemView);
sName = itemView.findViewById(R.id.lblSupplierName);
materialName = itemView.findViewById(R.id.lblMaterial);
CATEGORY = itemView.findViewById(R.id.lblLocation);
btnSelect=itemView.findViewById(R.id.btnSelect);
supplierClass sc=new supplierClass();
String id=user.getUid();
btnSelect.setOnClickListener(v -> {
ref= FirebaseDatabase.getInstance().getReference("dashboard");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
ref.child(id).setValue(sc.getsName());
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
});
}
}
Related
im trying to get int data from firestore but before that app crashes i dont know why when i try it as string it work i get it and i can list it but when i try it int app crashes even before get data
here is my code second part is my adapter logchat said 2 line is wrong i mark it with stairs for u
FirebaseFirestore firestore;
ArrayList<String> useremaillist;
ArrayList<Integer> userpointlist;
SkorAdapter skorAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_skor_board);
firestore=FirebaseFirestore.getInstance();
useremaillist=new ArrayList<>();
userpointlist=new ArrayList<>();
getscore();
RecyclerView skorboardrecyclerView=findViewById(R.id.recyclerView);
skorboardrecyclerView.setLayoutManager(new LinearLayoutManager(this));
skorAdapter=new SkorAdapter(useremaillist,userpointlist);
skorboardrecyclerView.setAdapter(skorAdapter);
}
public void getscore(){
CollectionReference collectionReference=firestore.collection("Kullanıcılar ve Skorlar");
collectionReference.orderBy("skor", Query.Direction.DESCENDING).addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#Nullable QuerySnapshot value, #Nullable FirebaseFirestoreException error) {
userpointlist.clear();
useremaillist.clear();
if(error!=null){
Log.e("tag",error.getLocalizedMessage());
}
if(value!=null){
for(DocumentSnapshot snapshot:value.getDocuments()){
Map<String,Object> userdatat=snapshot.getData();
String emailt=(String) userdatat.get("email");
int skor=(int) userdatat.get("skor");
useremaillist.add(emailt);
userpointlist.add(skor);
skorAdapter.notifyDataSetChanged();
}
}
}
});
}
** public class SkorAdapter extends RecyclerView.Adapter<SkorAdapter.Holder> {
private ArrayList<String> emaillistforadapter;
private ArrayList<Integer> pointlistforadapter;
public SkorAdapter(ArrayList<String> emaillistforadapter,ArrayList<Integer> pointlistforadapter ) {
this.emaillistforadapter = emaillistforadapter;
this.pointlistforadapter = pointlistforadapter;
}
#NonNull
#Override
public Holder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater=LayoutInflater.from(parent.getContext());
View view=layoutInflater.inflate(R.layout.skorboard_row,parent,false);
return new Holder(view);
}
#Override
public void onBindViewHolder(#NonNull SkorAdapter.Holder holder, int position) {
holder.useremailtext.setText(emaillistforadapter.get(position));
** holder.userpointtext.setText(pointlistforadapter.get(position));
}
#Override
public int getItemCount() {
return emaillistforadapter.size();
}
public class Holder extends RecyclerView.ViewHolder {
TextView useremailtext;
TextView userpointtext;
public Holder(#NonNull View itemView) {
super(itemView);
useremailtext=itemView.findViewById(R.id.kullanıcımailtext);
userpointtext=itemView.findViewById(R.id.kullanıcıpointtext);
}
}
The problem is in the adapter then.
You have a private ArrayList<Integer> pointlistforadapter; and the problem is that you are doing holder.userpointtext.setText(pointlistforadapter.get(position)); and setText() accepts a CharSeq and it lets you add an Int in paramter because it also has this signature :
And since it's not a resid it crashes.
What you can do is :
holder.userpointtext.setText(pointlistforadapter.get(position).toString());
I have a problem where the method "deleteItem" cannot be resolved at this line adapters.deleteItem(viewHolder.getAdapterPosition());even I have created that method at public void deleteItem(int position).Do I placed the method wrongly?
Java codes:
final FirestoreRecyclerAdapter adapters;
fStore = FirebaseFirestore.getInstance();
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
final String current = user.getUid();
Query query = fStore.collection("Users").document(user.getUid()).collection("Diary");
FirestoreRecyclerOptions<ModelClass> options = new FirestoreRecyclerOptions.Builder<ModelClass>()
.setQuery(query, ModelClass.class)
.build();
adapters = new FirestoreRecyclerAdapter<ModelClass, ModelViewHolder>(options) {
#NonNull
#Override
public ModelViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_diary, parent, false);
return new ModelViewHolder(view);
}
#Override
protected void onBindViewHolder(#NonNull ModelViewHolder holder, int position,
#NonNull ModelClass model) {
holder.date.setText(model.getDate());
holder.note.setText(model.getText());
holder.time.setText(model.getTime());
holder.divider.setText(model.getDivider());
}
public void deleteItem(int position) {
getSnapshots().getSnapshot(position).getReference().delete();
}
};
adapters.startListening();
recyclerView.setLayoutManager(new LinearLayoutManager(this));
SpacingItemDecoration itemDecorator = new SpacingItemDecoration(20);
recyclerView.addItemDecoration(itemDecorator);
recyclerView.setAdapter(adapters);
new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0,
ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
#Override
public boolean onMove(#NonNull RecyclerView recyclerView, #NonNull RecyclerView.ViewHolder viewHolder, #NonNull RecyclerView.ViewHolder target) {
return false;
}
#Override
public void onSwiped(#NonNull RecyclerView.ViewHolder viewHolder, int direction) {
adapters.deleteItem(viewHolder.getAdapterPosition());
}
}).attachToRecyclerView(recyclerView);
}
public class ModelViewHolder extends RecyclerView.ViewHolder {
TextView date, time, note, divider;
public ModelViewHolder(#NonNull View itemView) {
super(itemView);
date = itemView.findViewById(R.id.date_text);
time = itemView.findViewById(R.id.time_textview);
note = itemView.findViewById(R.id.note_textview);
divider = itemView.findViewById(R.id.line_textview);
}
}
You can't do it since adapters is a FirestoreRecyclerAdapter which doesn't contain this method.
Just extend the FirestoreRecyclerAdapter and use it.
public class CustomAdapter extends FirestoreRecyclerAdapter<....>{
public CustomAdapter(#NonNull FirestoreRecyclerOptions<....> options) {
super(options);
}
public void deleteItem(int i){ ... }
#Override
protected void onBindViewHolder(){....}
#Override
public ModelViewHolder onCreateViewHolder(){ ...}
}
I have a problem with Recycler view. it does not appear when i close and reopen the application.
1) Im using fragments, when i add an item to the recycler it appears normally:
https://i.stack.imgur.com/4Y8X6.png
2) When I close the app and then reopen it, the image doesn't load.
onCreateView of my fragment:
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
v= inflater.inflate(R.layout.fragment_home,container,false);
loadRecycler();
return v;
}
loadRecycler() method:
private void loadRecycler() {
DatabaseReference database = FirebaseDatabase.getInstance().getReference().child("Users").child("Animales");
database.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot dataSnapshot: snapshot.getChildren()){
for(DataSnapshot snap: dataSnapshot.getChildren()){
Animal animal = snap.getValue(Animal.class);
mlist.add(new AnimalAdapterData(animal.getNombre(),animal.getImageURL()));
}
}
recyclerView.getAdapter().notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
onViewCreated method:
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
recyclerView = v.findViewById(R.id.recycler_view);
adapter = new HomeAdapter(getActivity(),mlist);
GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(),2,GridLayoutManager.VERTICAL,false);
recyclerView.setLayoutManager(gridLayoutManager);
recyclerView.setHasFixedSize(true);
recyclerView.setAdapter(adapter);
}
HomeAdapter class:
public class HomeAdapter extends RecyclerView.Adapter<HomeAdapter.MyViewHolder> {
private Context context;
private List<AnimalAdapterData> mData;
public HomeAdapter(Context context, List<AnimalAdapterData> mData) {
this.context = context;
this.mData = mData;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.grid_item,parent,false);
return new MyViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
AnimalAdapterData currentItem = mData.get(position);
String imageUrl = currentItem.getImageURL();
String title = currentItem.getNombre();
holder.mTextView.setText(title);
Picasso.get().load(imageUrl).fit().centerInside().into(holder.mImageView);
}
#Override
public int getItemCount() {
return mData.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder{
ImageView mImageView;
TextView mTextView;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
mImageView = itemView.findViewById(R.id.imageView);
mTextView = itemView.findViewById(R.id.textView);
}
}
}
I think that im using correctly the onCreateView and onViewCreated method, but idk whats going on with this.
Tried using recycler view inside recycler view the first adapter works fine but the second adapter never runs
tired fixing it over and over nothing works....help
The second recycler view is retrieving data from Firebase
The Data from firebase is received but never set to the required text views.
Activity
public class ScheduleOrder extends AppCompatActivity implements IFirebaseLoadListener {
DeviceSession deviceSession;
UserSession userSession;
String Device_Id="",User_Id="";
MyItemAdapter myItemAdapter;
IFirebaseLoadListener iFirebaseLoadListener;
List<String> Name;
List<ItemData>itemData;
ItemData itemData1;
RecyclerView my_recycler_view;
DatabaseReference myData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_schedule_order);
itemData1=new ItemData();
deviceSession = new DeviceSession(getApplicationContext());
Device_Id = deviceSession.getDeviceDetails();
userSession = new UserSession(getApplicationContext());
final HashMap<String, String> user = userSession.getUserDetails();
User_Id = user.get(UserSession.User_Id);
FloatingActionButton myFab = (FloatingActionButton)findViewById(R.id.schedule_add);
myFab.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(),Schedule_Order.class);
startActivity(i);
finish();
}
});
myData=FirebaseDatabase.getInstance().getReference("Cart_Schedule"+"/"+Device_Id);
iFirebaseLoadListener=this;
my_recycler_view=findViewById(R.id.my_recyclr_view);
my_recycler_view.setHasFixedSize(true);
// my_recycler_view1.setHasFixedSize(true);
my_recycler_view.setLayoutManager(new LinearLayoutManager(this));
// my_recycler_view1.setLayoutManager(new LinearLayoutManager(this));
getFirebaseData();
}
private void getFirebaseData() {
myData.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
List<ItemGroup>itemGroups=new ArrayList<>();
Name=new ArrayList<>();
for(DataSnapshot groupSnapShot:dataSnapshot.getChildren()){
ItemGroup itemGroup=new ItemGroup();
itemGroup.setD_Time(groupSnapShot.child("d_Time").getValue(true).toString());
itemGroup.setF_Amount(groupSnapShot.child("f_Amount").getValue(true).toString());
for(DataSnapshot newdatasnap:groupSnapShot.child("listItem").getChildren()){
itemData1.setA_Item_name(newdatasnap.child("a_Item_name").getValue().toString());
itemData1.setB_Quantity(newdatasnap.child("b_Quantity").getValue().toString());
itemData1.setC_Price(newdatasnap.child("b_Quantity").getValue().toString());
Name.add(newdatasnap.child("a_Item_name").getValue().toString());
Name.add(newdatasnap.child("c_Price").getValue().toString());
Name.add(newdatasnap.child("b_Quantity").getValue().toString());
Log.d("JADOO", "onDataChange: ??? "+itemData1.getA_Item_name());
Log.d("JADOO", "onDataChange: ??? "+itemData1.getB_Quantity());
Log.d("JADOO", "onDataChange: ??? "+itemData1.getC_Price());
Log.d("JADOO", "onDataChange: ??? "+Name);}
Log.d("JADOO", "onDataChange: ====================================================");
itemGroups.add(itemGroup);
Name.clear();
}
iFirebaseLoadListener.onFirebaseLoadSuccess(itemGroups);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
iFirebaseLoadListener.onFirebaseLoadFailed(databaseError.getMessage());
}
});
}
#Override
public void onFirebaseLoadSuccess(List<ItemGroup> itemGroupList) {
Log.d("JADOO", "onDataChange: Setting Adapter");
MyItemGroupAdapter adapter = new MyItemGroupAdapter(ScheduleOrder.this,itemGroupList,itemData1);
my_recycler_view.setAdapter(adapter);
}
#Override
public void onFirebaseLoadFailed(String message) {
}
}
First Adapter Java file
public class MyItemGroupAdapter extends RecyclerView.Adapter<MyItemGroupAdapter.MyViewHolder> {
private Context context;
private List<ItemGroup>dataList;
private ItemData name;
public MyItemGroupAdapter(Context context, List<ItemGroup> dataList,ItemData data) {
this.context = context;
this.dataList = dataList;
this.name=data;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View itemView=LayoutInflater.from(context).inflate(R.layout.tempcartlayout,viewGroup,false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull final MyViewHolder myViewHolder, int i) {
MyItemAdapter itemListAdapter = new MyItemAdapter(context,name);
myViewHolder.timee.setText(dataList.get(i).getD_Time());
myViewHolder.cost.setText(dataList.get(i).getF_Amount());
Log.d("JADOO", "onDataChange: IN MY ITEM GRP ADAPTER "+name.getA_Item_name());
myViewHolder.recycler_view_item_list.setHasFixedSize(true);
myViewHolder.recycler_view_item_list.setLayoutManager(new CustomLinearLayoutManager(context,LinearLayoutManager.VERTICAL,false));
myViewHolder.recycler_view_item_list.setAdapter(itemListAdapter);
myViewHolder.recycler_view_item_list.setNestedScrollingEnabled(false);
myViewHolder.can.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(context, "Button More : "+myViewHolder.timee.getText()+" -- "+myViewHolder.cost.getText(), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return (dataList != null ? dataList.size() : 0);
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView timee,cost;
Button can;
RecyclerView recycler_view_item_list;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
timee=itemView.findViewById(R.id.reorder_time);
cost=itemView.findViewById(R.id.reorder_cost);
can=itemView.findViewById(R.id.button);
Log.d("JADOO", "onDataChange: VIEW HOLDER ");
recycler_view_item_list=itemView.findViewById(R.id.schedulecart);
}}}
Second Adapter File
private Context context;
private ItemData name123;
public MyItemAdapter(Context context, ItemData Item_Name) {
this.context = context;
this.name123=Item_Name;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View itemView= LayoutInflater.from(context).inflate(R.layout.cart_list_layout,viewGroup,false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder myViewHolder, final int i) {
Log.d("JADOO", "onBindViewHolder: IN MY ITEM ADAPTER");
ItemData itemData=new ItemData();
myViewHolder.m_name.setText(itemData.getA_Item_name());
myViewHolder.m_cost.setText(itemData.getC_Price());
myViewHolder.m_quant.setText(itemData.getB_Quantity());
}
#Override
public int getItemCount() {
return 0;
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView m_name,m_quant,m_cost;
IItemClickListener iItemClickListener;
public void setiItemClickListener(IItemClickListener iItemClickListener){
this.iItemClickListener=iItemClickListener;
}
public MyViewHolder(#NonNull View itemView) {
super(itemView);
m_name=itemView.findViewById(R.id.tv_menu_name1);
m_quant=itemView.findViewById(R.id.quantity);
m_cost=itemView.findViewById(R.id.amount);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
iItemClickListener.onItemClickListener(view,getAdapterPosition());
}}}
Error
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.food.pilo, PID: 28457
java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.recyclerview.widget.RecyclerView.setAdapter(androidx.recyclerview.widget.RecyclerView$Adapter)' on a null object reference
at com.food.pilo.ScheduleOrder.onFirebaseLoadSuccess(ScheduleOrder.java:161)
at com.food.pilo.ScheduleOrder$2.onDataChange(ScheduleOrder.java:143)
at com.google.firebase.database.Query$1.onDataChange(com.google.firebase:firebase-database##16.0.4:183)
at com.google.firebase.database.core.ValueEventRegistration.fireEvent(com.google.firebase:firebase-database##16.0.4:75)
at com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase-database##16.0.4:63)
at com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database##16.0.4:55)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7156)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:975)```
Your return value is 0 in Second adapter. Please add arraylist to second adapter.
#Override
public int getItemCount() {
return 0;
}
I think my_recycler_view=findViewById(R.id.my_recyclr_view); or
findViewById(R.id.schedulecart); returning null please check on these lines.
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;
}
}
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();
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);
}
}
}
Android sometimes is a little complicated, when it involves the full stack:
01 RecyclerView Adapter
/** 01. Some Adapter */
public class SomeAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private WeakReference<Context> mContext;
/** Constructor */
public SomeAdapter(#NonNull Context context) {
this.mContext = new WeakReference<>(context);
}
#NonNull
protected Context getContext() {
return this.mContext.get();
}
/** Call to Activity from within the adapter. */
private void someMethod() {
SomeActivity activity = (SomeActivity) getContext();
synchronized(activity) {activity.showLoginDialog();}
}
}
02 AppCompatActivity
/** 02. Some Activity */
public class SomeActivity extends AppCompatActivity {
#Nullable
private BaseFragment currentFragment = null;
/** Constructor */
public SomeActivity() {}
public void setCurrentFragment(Fragment fragment) {
this.currentFragment = fragment;
}
/** Call to the current Fragment. */
public void someMethod() {
if (currentFragment != null) {
currentFragment.someMethod();
}
}
}
03 Fragment
/** Some Fragment */
public class SomeFragment extends Fragment {
/** Constructor */
public SomeFragment() {}
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
((BaseActivity) context).setCurrentFragment(this);
}
#Override
public void onDetach() {
super.onDetach();
((BaseActivity) getActivity()).setCurrentFragment(this);
}
}
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