When i retrive children from firebase using recylceview TextView Won't Show - java

I'm using Android Studio when I run my app and add or show RecycleView list, text view shows only the title not data inside firebase this is the textviewaddCateogryclass
What would be causing this?
used the same data on firebase child.
firebase realtime database
Firebase
ModelCategoryClass
public class ModelCategoryClass {
//same variable in db
String id, category, uid;
long timestamp;
public ModelCategoryClass() {}
public ModelCategoryClass(String id, String category, String uid, long timestamp) {
this.id = id;
this.category = category;
this.uid = uid;
this.timestamp = timestamp;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
public long getTimestamp() {
return timestamp;
}
public void setTimestamp(long timestamp) {
this.timestamp = timestamp;
}
}
AdapterCategoryClass
public class AdapterCategoryClass extends RecyclerView.Adapter<AdapterCategoryClass.HolderCategory> {
private Context context;
private ArrayList<ModelCategoryClass> categoryClassArrayList;
//xml rows_categorys
private RowsCategorysBinding binding;
//constucor
public AdapterCategoryClass(Context context, ArrayList<ModelCategoryClass> categoryClassArrayList) {
this.context = context;
this.categoryClassArrayList = categoryClassArrayList;
}
///////////////
//generated from RecyclerView.Adapter<AdapterCategoryClass.HolderCategory>
#NonNull
#Override
public HolderCategory onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
//binding
binding = RowsCategorysBinding.inflate(LayoutInflater.from(context), parent, false);
return new HolderCategory(binding.getRoot());
//return new HolderCategory(RowsCategorysBinding.inflate(LayoutInflater.from(parent.getContext()),parent,false));
}
//getting data
#Override
public void onBindViewHolder(#NonNull HolderCategory holder, int position) {
ModelCategoryClass model = categoryClassArrayList.get(position);
String id = model.getId();
String category = model.getId();
String uid = model.getId();
long timestamp = model.getTimestamp();
//remove btn
//as we declred remove btn in HolderCatogory method
holder.removeBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(context,""+category,Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return categoryClassArrayList.size();
}
/////////////
//hold lists xml
public class HolderCategory extends RecyclerView.ViewHolder {
TextView textViewListCatt;
ImageButton removeBtn;
//constu
public HolderCategory(#NonNull View itemView) {
super(itemView);
textViewListCatt = binding.textViewListCat;
removeBtn = binding.removeBtn;
}
}
}
CategoryAddActivity class
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityCategoryAddBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
//init firebase auth
firebaseAuth = FirebaseAuth.getInstance();
ShowCategories();
private void ShowCategories() {
categoryClassArrayList = new ArrayList<>();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Categories");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
//clear array befor add data
categoryClassArrayList.clear();
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
//get data from child in database
ModelCategoryClass mod = dataSnapshot.getValue(ModelCategoryClass.class);
//add data to array
categoryClassArrayList.add(mod);
}
//start using adapter
adapterCategoryClass = new AdapterCategoryClass(CategoryAddActivity.this, categoryClassArrayList);
//get recycleListview rom xml and set it with defualt set method
binding.recycleList.setAdapter(adapterCategoryClass);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}

The following lines of code:
ModelCategoryClass model = categoryClassArrayList.get(position);
String id = model.getId();
String category = model.getId();
String uid = model.getId();
long timestamp = model.getTimestamp();
Should be changed to:
ModelCategoryClass model = categoryClassArrayList.get(position);
String id = model.getId();
String category = model.getCategory(); //👈
String uid = model.getUid(); //👈
long timestamp = model.getTimestamp();
Meaning that you need to call the corresponding getters. But that's not the entire problem. You aren't displaying something because you aren't setting those values to their corresponding views. To solve this, you have to create inside your HolderCategory class a method that actually binds the data to the views. For example, to set the category, you should use something like this:
void setCategory(String category) {
binding.textViewListCat.setText(category);
}
And then call this method from inside your onBindViewHolder method like this:
holder.setCategory(category);

Related

FireBase Recycler Adapter doesn't retrieve data from FireBase

My database looks like this
I'm trying to fetch all this data from that USER ID inside Cart. But my RecyclerView shows nothing. After checking, the adapter.getItemCount() returns 0. Where did I wrong? This is my code :
onStart()
private void loadData(){
auth = FirebaseAuth.getInstance().getCurrentUser();
userID = auth.getUid();
final DatabaseReference cartList = FirebaseDatabase.getInstance().getReference().child("Cart");
FirebaseRecyclerOptions<Cart> options =
new FirebaseRecyclerOptions.Builder<Cart>()
.setQuery(cartList.child(userID),Cart.class).build();
FirebaseRecyclerAdapter<Cart,CartHolder> adapter
= new FirebaseRecyclerAdapter<Cart, CartHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull CartHolder holder, int position, #NonNull Cart model) {
holder.txtGia.setText(model.getTotal());
}
#NonNull
#Override
public CartHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cart_item,parent,false);
CartHolder holder = new CartHolder(view);
return holder;
}
};
recyclerView.setAdapter(adapter);
adapter.startListening();
}
Model
public class Cart {
public String pID,num,time,addr,total,userID;
public Cart(){}
public Cart(String num,String pID,String time,String addr,String total,String userID) {
this.num = num;
this.pID = pID;
this.time = time;
this.addr = addr;
this.total = total;
this.userID = userID;
}
public String getNum() {
return num;
}
public String getpID() {
return pID;
}
public String getTime() {
return time;
}
public String getAddr() {
return addr;
}
public String getTotal() {
return total;
}
public String getUserID() {
return userID;
}
}
and ViewHolder
public class CartHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public ImageView shibaImg;
public TextView txtTen,txtMota,txtGia,txtThoigian;
ItemClickListener listener;
public CartHolder(#NonNull View itemView) {
super(itemView);
shibaImg = (ImageView) itemView.findViewById(R.id.cart_item_img);
txtTen = (TextView) itemView.findViewById(R.id.cart_item_ten);
txtMota = (TextView) itemView.findViewById(R.id.cart_item_mota);
txtGia = (TextView) itemView.findViewById(R.id.cart_item_gia);
txtThoigian = (TextView) itemView.findViewById(R.id.cart_item_history);
}
public void setItemClickListener(ItemClickListener listener){
this.listener = listener;
}
#Override
public void onClick(View v) {
listener.onClick(v, getAdapterPosition(),false);
}
}
This code seems to be the problem:
cartList.orderByChild("userID").equalTo(userID)
This code takes every child nodes directly under cartList and orders them on their userID property. But there is no userID property in your screenshot, so this results in an empty list.
My best guess is that the key of each node under cartList is the user ID, in which case you can instead use:
cartList.child(userID)
So:
final DatabaseReference cartList = FirebaseDatabase.getInstance().getReference().child("Cart");
FirebaseRecyclerOptions<Cart> options =
new FirebaseRecyclerOptions.Builder<Cart>()
.setQuery(cartList.child(userID),Cart.class).build();
I've finally figured it out.
For some reason, RecyclerView on my CartActivity needs time to load data in (Maybe cause I have 3 RecyclerView on HomeActivity and sometimes data show up and sometimes It don't, usually 1 or 2 / 3 RecyclerViews show data). When I reload (press back and Start Activity again), RecyclerView will appear and show data.

Firebase Database search query issue

I'm trying to create a search feature where users can search other registered. i managed to get the search to work but its not giving the desired result. No matter what keyword i input, it brings up all the registered users on the search result instead of just the ones related to the keyword.
i'm no expert in java but ive tried changing and rearranging some lines, but the outcome is still the same.
private void SearchPeopleAndFriends(String searchBoxInput)
{
FirebaseRecyclerOptions<FindFriends> options = new FirebaseRecyclerOptions.Builder<FindFriends>().
setQuery(UsersRef, FindFriends.class).build(); //query build past the query to FirebaseRecyclerAdapter
FirebaseRecyclerAdapter<FindFriends, FindFriendsActivity.FindFriendViewHolder> adapter=new FirebaseRecyclerAdapter<FindFriends, FindFriendViewHolder>(options)
{
#Override
protected void onBindViewHolder(#NonNull FindFriendsActivity.FindFriendViewHolder holder, int position, #NonNull FindFriends model)
{
holder.username.setText(model.getFullname());
holder.status.setText(model.getStatus());
Picasso.get().load(model.getProfileimage()).into(holder.profileimage);
holder.itemView.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent findOthersIntent = new Intent(FindFriendsActivity.this, FindFriendsActivity.class);
startActivity(findOthersIntent);
}
});
}
#NonNull
#Override
public FindFriendsActivity.FindFriendViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i)
{
View view= LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.all_user_display_layout,viewGroup,false);
FindFriendsActivity.FindFriendViewHolder viewHolder=new FindFriendsActivity.FindFriendViewHolder(view);
return viewHolder;
}
};
SearchResultList.setAdapter(adapter);
adapter.startListening();
}
public class FindFriendViewHolder extends RecyclerView.ViewHolder
{
TextView username, status;
CircleImageView profileimage;
public FindFriendViewHolder(#NonNull View itemView)
{
super(itemView);
username = itemView.findViewById(R.id.all_user_profile_name);
status = itemView.findViewById(R.id.all_user_status);
profileimage = itemView.findViewById(R.id.all_user_profile_pic);
}
}
Instead of it bringing user related to the keyword in the search result, it brings up all the users in the database. my goal is for it to only display whatever users name contains the keyword that was inputed
This is my model class
public class FindFriends {
public String profileimage, fullname, status;
public FindFriends()
{
}
public String getProfileimage() {
return profileimage;
}
public void setProfileimage(String profileimage) {
this.profileimage = profileimage;
}
public String getFullname() {
return fullname;
}
public void setFullname(String fullname) {
this.fullname = fullname;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public FindFriends(String profileimage, String fullname, String status) {
this.profileimage = profileimage;
this.fullname = fullname;
this.status = status;
}
}
My Firebase Refs:
mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
UsersRef = FirebaseDatabase.getInstance().getReference().child("Users");

How to Retrieve Value in RecyclerView I tried a lot but it Retrieve a Null Value from Generated ID by Firebase after Push Data in Database in Android

How to retrieve value in RecyclerView I tried a lot but it retrieve a null value from generated id by Firebase after push data in database and if I don't using this method "push" the data stored in second id directly and retrieved well in Android and in log cat:
W/ClassMapper: No setter/field for -L9VWgoCymRWj9zbgK5H [image for database stracture][1]
This is my code:
public class TasksListActivity extends AppCompatActivity {
RecyclerView recyclerView;
TaskAdapter adapter;
List<Tasks>tasksList;
FirebaseDatabase FDB;
DatabaseReference DBR;
private FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tasks_list);
recyclerView=(RecyclerView) findViewById(R.id.testingss);
RecyclerView.LayoutManager manager=new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(manager);
recyclerView.setHasFixedSize(true);
mAuth = FirebaseAuth.getInstance();
tasksList=new ArrayList<>();
adapter=new TaskAdapter(tasksList);
FDB=FirebaseDatabase.getInstance();
GetDataFirebase();
}
void GetDataFirebase (){
FirebaseUser currentUser = mAuth.getCurrentUser();
final String currentid=currentUser.getUid();
DBR=FDB.getReference("tasks").child(currentid);
DBR.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Tasks data=dataSnapshot.getValue(Tasks.class);
//Toast.makeText(getApplicationContext(),tas,Toast.LENGTH_SHORT).show();
tasksList.add(data);
adapter.notifyDataSetChanged();
recyclerView.setAdapter(adapter);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
public class TaskAdapter extends RecyclerView.Adapter<TaskAdapter.TaskViewHolder>{
List<Tasks> data=new ArrayList<>();
public TaskAdapter(List<Tasks> tasks){
this.data=tasks;
}
#Override
public TaskAdapter.TaskViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.taskslistitem,parent,false);
return new TaskViewHolder(view);
}
#Override
public void onBindViewHolder(TaskAdapter.TaskViewHolder holder, int position) {
Tasks tasks=data.get(position);
holder.taskName.setText(tasks.getmTaskname());
Toast.makeText(getApplicationContext(),tasks.getmTaskname(),Toast.LENGTH_SHORT).show();
//Toast.makeText(getApplication(),tasks.getmTaskname(),Toast.LENGTH_SHORT).show();
// Toast.makeText(getApplicationContext(),holder.taskName.getText(),Toast.LENGTH_SHORT).show();
}
#Override
public int getItemCount() {
return data.size();
}
public class TaskViewHolder extends RecyclerView.ViewHolder {
TextView taskName;
public TaskViewHolder(View itemView) {
super(itemView);
taskName=(TextView) itemView.findViewById(R.id.tasksnameId);
}
}
}
}
the class about tasks model
public class Tasks {
private String mMemberEmail;
private String mTaskname;
private String mTaskDsc;
private String mTaskDeadline;
public Tasks() {
}
public Tasks(String mMemberEmail, String mTaskname, String mTaskDsc, String mTaskDeadline) {
this.mMemberEmail = mMemberEmail;
this.mTaskname = mTaskname;
this.mTaskDsc = mTaskDsc;
this.mTaskDeadline = mTaskDeadline;
}
public String getmMemberEmail() {
return mMemberEmail;
}
public void setmMemberEmail(String mMemberEmail) {
this.mMemberEmail = mMemberEmail;
}
public String getmTaskname() {
return mTaskname;
}
public void setmTaskname(String mTaskname) {
this.mTaskname = mTaskname;
}
public String getmTaskDsc() {
return mTaskDsc;
}
public void setmTaskDsc(String mTaskDsc) {
this.mTaskDsc = mTaskDsc;
}
public String getmTaskDeadline() {
return mTaskDeadline;
}
public void setmTaskDeadline(String mTaskDeadline) {
this.mTaskDeadline = mTaskDeadline;
}
}
final Tasks tasks=new Tasks(mMemberEmail,mTasksName,mTaskDsc,mTaskDeadline);
mUserDatabase.child("tasks").child(current_id).child(id).push().setValue(tasks).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
mAuth = FirebaseAuth.getInstance();
user = mAuth.getCurrentUser();
String current_id = user.getUid();
Tasks tasks=new Tasks(mMemberEmail,mTasksName,mTaskDsc,mTaskDeadline);
String id = child.getKey();
mUserDatabase.child("tasks").child(id).child(current_id).push().setValue(tasks);
}
});
}
You are getting the following warning:
W/ClassMapper: No setter/field for -L9VWgoCymRWj9zbgK5H
Because you are using wrong getters for your fields. The correct getter for a field that looks like this:
private String mMemberEmail;
Should be:
public String getMMemberEmail() { //See the first capital M
return mMemberEmail;
}
The correct naming for the fields and getters inside a model should be:
public class Tasks {
private String memberEmail;
private String taskName;
private String taskDsc;
private String taskDeadline;
public Tasks() {}
public Tasks(String memberEmail, String taskName, String taskDsc, String taskDeadline) {
this.memberEmail = memberEmail;
this.taskName = taskName;
this.taskDsc = taskDsc;
this.taskDeadline = taskDeadline;
}
public String getMemberEmail() {return memberEmail;}
public String getTaskName() {return taskName;}
public String getTaskDsc() {return taskDsc;}
public String getTaskDeadline() {return taskDeadline;}
}
So remember, when the Firebase Realtime Database SDK deserializes objects coming from the database, is looking for fields that follow the principles of the JavaBeans and are named accordingly to Java Naming Conventions. So the corresponding getter for a field like memberEmail is getMemberEmail() and not getmemberEmail(). To make it work entirely, delete old data and add fresh one.

DatabaseException: Can't convert object of type java.lang.String to type StreetClass

I want to display Login user details in RecyclerView from Firebase database but I am facing the following error:
com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.String to type.
This is my model class:
public class StreetClass {
private String id;
private String semail;
private String sname;
private String stype;
private String sdetail;
private String slocation;
private String sdate;
private String imgurl;
public StreetClass(){}
public StreetClass(String id, String semail, String sname, String stype, String sdetail, String slocation, String sdate, String imgurl) {
this.id = id;
this.semail = semail;
this.sname = sname;
this.stype = stype;
this.sdetail = sdetail;
this.slocation = slocation;
this.sdate = sdate;
this.imgurl = imgurl;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getSemail() {
return semail;
}
public void setSemail(String semail) {
this.semail = semail;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public String getStype() {
return stype;
}
public void setStype(String stype) {
this.stype = stype;
}
public String getSdetail() {
return sdetail;
}
public void setSdetail(String sdetail) {
this.sdetail = sdetail;
}
public String getSlocation() {
return slocation;
}
public void setSlocation(String slocation) {
this.slocation = slocation;
}
public String getSdate() {
return sdate;
}
public void setSdate(String sdate) {
this.sdate = sdate;
}
public String getImgurl() {
return imgurl;
}
public void setImgurl(String imgurl) {
this.imgurl = imgurl;
}
}
recyclerview Adapter class:
public class StreetAdapter extends RecyclerView.Adapter<StreetAdapter.ViewHolder> {
Context context;
private List<StreetClass>listdata ;
public StreetAdapter(Context context, List<StreetClass> list) {
this.listdata = list;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.show_items, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
StreetClass AllDetails = listdata.get(position);
holder.NameTextView.setText(AllDetails.getSname());
holder.DetailTextView.setText(AllDetails.getSdetail());
holder.DateTextView.setText(AllDetails.getSdate());
holder.LocationTextView.setText(AllDetails.getSlocation());
holder.TypeTextView.setText(AllDetails.getStype());
Picasso.with(context).load(AllDetails.getImgurl()).resize(120, 60).into(holder.ImageTextView);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = holder.getAdapterPosition();
final Intent intent;
if (position == 0){
intent = new Intent(context, ShowStreetDetails.class);
} else if (position == 1){
intent = new Intent(context, ElectricityActivity.class);
} else {
intent = new Intent(context, Water_Supply_Activity.class);
}
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return listdata.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
public TextView NameTextView;
public TextView DetailTextView;
public TextView DateTextView;
public TextView LocationTextView;
public TextView TypeTextView;
public ImageView ImageTextView;
public ViewHolder(View itemView) {
super(itemView);
NameTextView = itemView.findViewById(R.id.ShowNameTextView);
DetailTextView = itemView.findViewById(R.id.ShowDetailTextView);
DateTextView = itemView.findViewById(R.id.ShowDateTextView);
LocationTextView = itemView.findViewById(R.id.ShowLocationTextView);
TypeTextView = itemView.findViewById(R.id.ShowTypeTextView);
ImageTextView = itemView.findViewById(R.id.ShowImageView);
}
}
}
Here I store my all data:
StreetClass street = new StreetClass();
street.setSname(nameString);
street.setStype(typeString);
street.setSdetail(detailString);
street.setSlocation(locationString);
street.setSdate(dateString);
street.setImgurl(ImageUrl);
String RecordIDFromServer = databaseReference.push().getKey();
// Adding the both name and number values using student details class object using ID.
databaseReference.child(RecordIDFromServer).setValue(street);
// Showing Toast message after successfully data submit.
Toast.makeText(StreetActivity.this,"Data Inserted Successfully into Firebase Database", Toast.LENGTH_LONG).show();
Mainactivity
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference databaseStatus = rootRef.child("Street Problems");
String uid = firebaseAuth.getInstance().getCurrentUser().getUid();
databaseStatus.child(uid).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
for (DataSnapshot ds : snapshot.getChildren()) {
for (DataSnapshot dSnapshot : ds.getChildren()) {
StreetClass streetClass = dSnapshot.getValue(StreetClass.class);
Log.d("Show", streetClass.getSname() == null ? "" : streetClass.getSname());
list.add(streetClass);
}
adapter = new StreetAdapter(ShowStreetDetails.this, list);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
progressDialog.dismiss();
}
and this is my database structure
To get the name of a single user, please use the following code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference yourRef = rootRef.child("Street Problems").child(uid);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
StreetClass streetClass = ds.getValue(StreetClass.class);
Log.d("TAG", streetClass.getSname());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
yourRef.addListenerForSingleValueEvent(eventListener);
I see in your picture that you are using the push() method to create another node which is not necessary. You can simply add those properties beneath the uid.
The problem is that you have an extra forEach loop in your onDataChange method. Simply remove it and it should be fine:
#Override
public void onDataChange(DataSnapshot snapshot) {
for (DataSnapshot dSnapshot : snapshot.getChildren()) {
StreetClass streetClass = dSnapshot.getValue(StreetClass.class);
Log.d("Show", streetClass.getSname() == null ? "" : streetClass.getSname());
list.add(streetClass);
}
adapter = new StreetAdapter(ShowStreetDetails.this, list);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
progressDialog.dismiss();
}

Firebase UI 3.0.0: Retrieve data to recycle view

Can anyone help me to retrieve data from the node "foods" and put it in the RecyclerView. These are the file I've been working on but it turns out to be an empty list. I have viewed a tutorial on Internet but most of them were with an older version of Firebase. Recently, Firebase UI has been updated and the data binding process has changed to their new FirebaseRecyclerAdapter structure
This is my database structure:
"foods" : {
"AntipastoSalad" : {
"duration" : "30",
"img" : "https://firebasestorage.googleapis.com/v0/b/mealplanner-ec8ca.appspot.com/o/res%2Fsalad.jpg?alt=media&token=257d4392-8a1f-4fb7-84b5-b63abb4643f4",
"name" : "Antipasto salad",
"type" : "Salad"
},
This is my activity:
private RecyclerView mRecycleView;
private Query query;
private FirebaseRecyclerOptions<Meal> options;
private DatabaseReference mDatabase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_food_list_row);
mDatabase = FirebaseDatabase.getInstance().getReference().child("foods");
//Recycle View
mRecycleView = (RecyclerView) findViewById(R.id.meal_items);
mRecycleView.setHasFixedSize(true);
mRecycleView.setLayoutManager(new LinearLayoutManager(this));
}
#Override
protected void onStart() {
super.onStart();
query = FirebaseDatabase.getInstance().getReferenceFromUrl("https://mealplanner-ec8ca.firebaseio.com/foods/AntipastoSalad");
options = new FirebaseRecyclerOptions.Builder<Meal>()
.setQuery(query, Meal.class)
.build();
FirebaseRecyclerAdapter<Meal, FoodListRowActivity.MealRowHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Meal, FoodListRowActivity.MealRowHolder>(
options) {
#Override
public FoodListRowActivity.MealRowHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.food_row, parent, false);
return new FoodListRowActivity.MealRowHolder(v);
}
#Override
protected void onBindViewHolder(FoodListRowActivity.MealRowHolder holder, int position, Meal current) {
holder.setTitle(current.getName());
String duration = current.getDuration() + "min";
holder.setDuration(duration);
}
};
//Populate Item into Adapter
mRecycleView.setAdapter(firebaseRecyclerAdapter);
mRecycleView.addOnItemTouchListener(new RecycleViewItemClickListener(this, mRecycleView, new RecycleViewItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
Intent viewMeal = new Intent(FoodListRowActivity.this, CookingInstructionActivity.class);
startActivity(viewMeal);
}
#Override
public void onLongItemClick(View view, int position) {
//TODO: DELETE
}
}));
}
public static class MealRowHolder extends RecyclerView.ViewHolder {
View mView;
public MealRowHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setTitle(String title) {
TextView foodTitle = (TextView) mView.findViewById(R.id.list_item_foodList_name);
foodTitle.setText(title);
}
public void setDuration(String title) {
TextView foodDuration = (TextView) mView.findViewById(R.id.list_item_foodList_calories);
foodDuration.setText(title);
}
}
}
and class structure:
public class Meal{
private String img;
private String duration;
private String name;
private String instruction;
public Meal(){
}
public Meal (String img, String duration, String name, String instruction){
this.img = img;
this.name = name;
this.duration = duration;
this.instruction = instruction;
}
public void update(String duration, String name, String instruction)
{
this.name = name;
this.duration = duration;
this.instruction = instruction;
}
public String getName(){
return name;
}
public String getDuration() {
return duration;
}
public String getInstruction() {
return instruction;
}
public String getImg(){return img;}
The query specified in the setQuery() method should be a reference to the root of the list you want to show in the RecyclerView, so like this:
query = FirebaseDatabase.getInstance().getReference().child("foods");
You also need to call startListening() on the adapter to instruct it to start retrieving data from the database.
From the FirebaseRecyclerAdapter lifecycle documentation:
The FirebaseRecyclerAdapter uses an event listener to monitor changes to the Firebase query. To begin listening for data, call the startListening() method. You may want to call this in your onStart() method. Make sure you have finished any authentication necessary to read the data before calling startListening() or your query will fail.
#Override protected void onStart() {
super.onStart();
adapter.startListening();
}
Similarly, the stopListening() call removes the event listener and all data in the adapter. Call this method when the containing Activity or Fragment stops:
#Override protected void onStop() {
super.onStop();
adapter.stopListening();
}
Please override getItemCount() method of FirebaseRecyclerAdapter.
#Override
public int getItemCount() {
return 1;
}
Reference.
This is how I'm retrieving my data in recyclerview using Firebase UI:
private FirebaseRecyclerAdapter<TaskPOJO, TaskViewHolder> adapter;
private void loadTasks() {
database = FirebaseDatabase.getInstance();
tasks = database.getReference("Tasks");
adapter = new FirebaseRecyclerAdapter<TaskPOJO, TaskViewHolder>(TaskPOJO.class, R.layout.task_item, TaskViewHolder.class, tasks) {
#Override
protected void populateViewHolder(TaskViewHolder viewHolder, final TaskPOJO model, int position) {
Log.wtf("valueTEst", "populateViewHolder: "+model.toString() );
Log.wtf("TEstScript1", "populateViewHolder: "+model.getTitle() );
viewHolder.title.setText(model.getTitle());
viewHolder.desc.setText(model.getDescripttion()+"\n");
viewHolder.remaining.setText(model.getRemaining()+"/"+model.getPoint());
viewHolder.points.setText("Points "+model.getRemaining());
Glide.with(viewHolder.title.getContext())
.load(model.getImage())
.into(viewHolder.image);
viewHolder.setClickListener(new ItemClickListener() {
#Override
public void onClick(View view, int position, boolean isLongClick) {
Toast.makeText(getActivity(), "" /*+ model.getTitle()*/, Toast.LENGTH_SHORT).show();
Intent TaskPOJODetail = new Intent(getActivity(), Main.class);
TaskPOJODetail.putExtra("value","detail");
TaskPOJODetail.putExtra("taskId",adapter.getRef(position).getKey());
startActivity(TaskPOJODetail);
}
});
}
};
progressBar.setVisibility(View.GONE);
recyclerViewTasks.setAdapter(adapter);
}
this is my firebase structure :
hope this will help you.

Categories