【问题标题】:Need help in retrieving hash map values from Firestore (Android)在从 Firestore (Android) 检索哈希映射值时需要帮助
【发布时间】:2019-11-23 21:32:24
【问题描述】:

我在从 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;
    }
}

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

【问题讨论】:

  • 你遇到了什么错误?
  • 您好,没有错误,但是当我尝试将其放在回收站视图中时收到空值。

标签: java android google-cloud-firestore


【解决方案1】:

您需要将 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 {}

【讨论】:

  • 谢谢!你拯救了我的一天。
【解决方案2】:

您似乎将OrderItems 对象存储在单个文档中。如果您在特定对象上附加侦听器,则返回的对象是 DocumentSnapshot 类型:

DocumentSnapshot 包含从 Firestore 数据库中的文档读取的数据。可以使用 getData() 或 get() 方法提取数据。

如果您打算使用getData(),则会返回一个Map 对象,因此您可以简单地对其进行迭代并获取所需的数据。但请记住,您无法直接获取OrderItems 对象的列表,您需要为此编写代码。

我不确定您想要实现什么,但在您的情况下,更合适的解决方案是将这些项目作为单独的文档存储在集合中。通过这种方式,您可以获取订单集合中的所有文档(OrderItems 对象)并将它们显示在RecyclerView 中,正如我在以下帖子中的回答中所述:

编辑:

如果您需要将自定义对象数组映射到列表中,请查看以下文章:

【讨论】:

  • 嗨维奥里!我可以帮助您了解其他信息吗?如果您认为我的回答对您有所帮助,请考虑通过单击左侧投票箭头下方的复选标记(✔️)来接受它。应将颜色更改为绿色。我会很感激的。谢谢!
猜你喜欢
  • 2019-03-13
  • 2020-06-06
  • 2010-11-18
  • 1970-01-01
  • 1970-01-01
  • 2017-10-04
  • 1970-01-01
  • 2014-05-10
相关资源
最近更新 更多