首页 > 解决方案 > 在从 Firestore (Android) 检索哈希映射值时需要帮助

问题描述

我无法从 Firestore 中检索哈希映射值。我上传值没有问题,但我在检索它们时遇到了困难。 这是我的 Firestore 数据库。

这是我的构造函数:

public class OrderItems {
    private String uid;
    private String product;
    private int qty;
    private int price;
    private int totalPrice;

    public OrderItems(){

    }

    public OrderItems(String uid, String product, int qty, int price) {
        this.uid = uid;
        this.product = product;
        this.qty = qty;
        this.price = price;
    }

    public String getUid() {
        return uid;
    }

    public String getProduct() {
        return product;
    }

    public int getQty() {
        return qty;
    }

    public int getPrice() {
        return price;
    }

    public int getTotalPrice() {
        return qty * price;
    }

    public void setTotalPrice(int totalPrice) {
        this.totalPrice = totalPrice;
    }
}

我的哈希映射构造函数:

public class OrderObject {

    private HashMap<String, OrderItems> orders;

    public OrderObject(){

    }

    public OrderObject(HashMap<String, OrderItems> orders) {
        this.orders = orders;
    }

    public HashMap<String, OrderItems> getOrders() {
        return orders;
    }
}

如何通过数组列表使用构造函数存储对象?之后如何访问各个字段?谢谢!

标签: javaandroidgoogle-cloud-firestore

解决方案


您需要将 DocumentSnapshot 转换为 HashMap

db.collection("Deliveries").document("your_document_id").get()
.addOnSuccessListener {
val obj = it.get("Coconut") as HashMap<*, *>
Log.d("TAG",   it.get("Coconut").toString())
// This will print the whole map value
Log.d("TAG", obj.get("qty").toString())
}.addOnFailureListener {}

推荐阅读