简体   繁体   中英

How to retrieve list of model objects from firebase databse

在此处输入图像描述

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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