简体   繁体   English

如何从 firebase 数据库中检索 model 对象列表

[英]How to retrieve list of model objects from firebase databse

在此处输入图像描述

Model Class Model Class


    public String id;
    public String total;
    public List<CartModel> orderList;
    public String currentDate;
    public String orderBy;

I want to fetch these objects but unfortunately can't do this.我想获取这些对象,但不幸的是不能这样做。 I'm accessing this list in my adapter class like the following way but getting null value.我正在我的适配器 class 中访问此列表,如下所示,但获得 null 值。

protected void onBindViewHolder(@NonNull final OrderHolder holder, int position, @NonNull Orders model) {

        List<CartModel> list = new ArrayList<>();
        list = model.getOrderList();
        Log.i("Orders", list+"");

        holder.dateTime.setText(model.getCurrentDate());
        holder.grandTotal.setText("Total "+model.getTotal());
        holder.orderBy.setText(model.getOrderBy());

    }

Please provide me a valid solution for doing this请为我提供一个有效的解决方案

The name of your field in the Java code doesn't match the property name in the JSON. Java 代码中的字段名称与 JSON 中的属性名称不匹配。

To make them match, change:要使它们匹配,请更改:

public List<CartModel> orderList;

To:至:

public List<CartModel> orderItems;
String userid="your unique id";
String orderid="your unique id";
DatabaseReference database=FirebaseDatabase.getInstance().getReference()
databse.child("yourroot")
       .child("Users")
       .child(userid)
       .child("Orders")
       .child(orderid)
       .child("orderItems")
       .addValueEventListener(new ValueEventListener {
            @Override 
            void onCancelled(@NonNull DatabaseError error) {
                //handle error as per your requirement
            }

            @Override 
            void onDataChange(@NonNull DataSnapshot snapshot) {
                YourModel model=snapshot.getValue(YourModel.class)
                //use the model or add to adapter payload and notify it on mainthread
            }
        })

Note: you may get DatabaseException if your model class is not an appropriate class to hold values from the DB.注意:如果您的 model class 不是一个合适的 class 来保存来自 DB 的值,您可能会得到DatabaseException

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM