firebase 如何使用Firestore获取当前登录用户的文档?[duplicate]

wyyhbhjk  于 2022-11-17  发布在  其他
关注(0)|答案(2)|浏览(134)

此问题在此处已有答案

How can I get document values from a collection for the logged in user into a using Firestore?(1个答案)
昨天关门了。

我在我的Firestore中有这样的结构,我希望登录的用户能够获得所有的图像URL和其他字段,如名称,价格和与该用户ID相关的描述。这些信息将被加载到一个recyclerView中。

这是物料模型

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;
}

}

这是我尝试过的代码,它会破坏我的应用程序:

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();
            }
        }
5vf7fwbs

5vf7fwbs1#

尝试以下查询以获取单个用户的多个文档-

db.collection("images")
        .whereEqualTo("user_id", FirebaseAuth.getInstance().getCurrentUser().getUid())
        .get()
        .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
            @Override
            public void onComplete(@NonNull Task<QuerySnapshot> task) {
                if (task.isSuccessful()) {  
                    for (QueryDocumentSnapshot document : task.getResult()) {
                           Item item = new Item();
                           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();
                } else {
                    Log.d(TAG, "Error getting documents: ", task.getException());
                }
            }
        });

检查文档中是否有更多此类查询-https://firebase.google.com/docs/firestore/query-data/queries

euoag5mw

euoag5mw2#

不需要分别获取每个字段的值。您可以直接将Realtime Database中的子对象Map到Item类型的对象中。为了能够做到这一点,您必须如下更改类的声明:

public class Item {
    private String name;
    private String price;
    private String description;
    private String image;
    private String userId;

    public Item(String name, String price, String description, String image, String userId) {
        this.name = name;
        this.price = price;
        this.description = description;
        this.image = image;
        this.userId = userId;

    }
    public Item(){

    }
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPrice() {
        return price;
    }

    public void setPrice(String price) {
        this.price = price;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getImage() {
        return image;
    }

    public void setImage(String image) {
        this.image = image;
    }

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }
}

为什么?因为类中字段的名称应该命名数据库中存在的名称。
现在,为了获得与登录用户相对应的图像,您必须初始化列表、适配器和RecyclerView,并创建如下所示的查询:

itemList = new ArrayList<>();
shoeAdapter = new ShoeAdapter(MainActivity.this, itemList);
recyclerView.setAdapter(shoeAdapter);

String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
FirebaseFirestore db = FirebaseFirestore.getInstance();
Query queryByUserId = db.collection("images").whereEqualTo("userId", uid);
queryByUserId.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
    @Override
    public void onComplete(@NonNull Task<QuerySnapshot> task) {
        if (task.isSuccessful()) {
            for (QueryDocumentSnapshot document : task.getResult()) {
                if (document != null) {
                    Item item = document.toObject(Item.class);
                    itemList.add(item);
                    Log.d("TAG", item.getName());
                }
            }
            shoeAdapter.notifyDataSetChanged();
        } else {
            Log.d("TAG", task.getException().getMessage()); //Never ignore potential errors!
        }
    }
});

我所做的更改:
1.不需要使用while循环,只需要检查空值。
1.我已经在异步操作之外添加了与UI相关的声明。一旦获取Item对象的操作完成,我们只通知适配器有关的更改。
1.始终处理错误。

相关问题