I have this structure in my Firestore, I want the logged-in user to be able to get all image URLs and other fields such as name, price, and description that are associated with that userID. This info will be loaded into a recyclerView.
This is the Item Model
package com.bac.shoesrecyclerview;
public class Item {
private String itemName;
private String itemPrice;
private String itemDescription;
private String itemImage;
public Item(String itemName, String itemPrice, String itemDescription, String itemImage) {
this.itemName = itemName;
this.itemPrice = itemPrice;
this.itemDescription = itemDescription;
this.itemImage = itemImage;
}
public Item(){
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public String getItemPrice() {
return itemPrice;
}
public void setItemPrice(String itemPrice) {
this.itemPrice = itemPrice;
}
public String getItemDescription() {
return itemDescription;
}
public void setItemDescription(String itemDescription) {
this.itemDescription = itemDescription;
}
public String getItemImage() {
return itemImage;
}
public void setItemImage(String itemImage) {
this.itemImage = itemImage;
}
}
This is the code i tried and crushes my app :
fStore.collection("images").document(FirebaseAuth.getInstance().getCurrentUser().getUid()).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if(task.isSuccessful()){
DocumentSnapshot document = task.getResult();
Item item = new Item();
itemList = new ArrayList<>();
while (document.exists()){
item.setItemName(document.getString("name"));
item.setItemPrice(document.getString("price"));
item.setItemDescription(document.getString("description"));
item.setItemImage(document.getString("image"));
itemList.add(item);
}
shoeAdapter = new ShoeAdapter(MainActivity.this, itemList);
recyclerView.setAdapter(shoeAdapter);
shoeAdapter.notifyDataSetChanged();
}
}
2
Answers
Try below query to get multiple document for single user-
Check document for more such queries – https://firebase.google.com/docs/firestore/query-data/queries
There is no need to get the value of each field separately. You can directly map a child in the Realtime Database into an object of type
Item
. In order to be able to do that, you have to change the declaration of the class like this:Why? Because the name of the fields inside the class should name the name that exists in the database.
Now, in order to get the images that correspond to a logged-in user, you have to initialize the list, the adapter, and the RecyclerView and create a query that looks like this:
The changes that I made: