如何使用子级在recyclerview中显示Firebase中的特定数据?

时间:2018-10-06 12:34:20

标签: android firebase firebase-realtime-database

例如,我想显示所有fs_ID等于FS02的订单。我在下面提供了我的Firebase的屏幕截图:

My firebase

这是我当前的代码:

public class NewOrders extends AppCompatActivity {

public RecyclerView recyclerView;
public RecyclerView.LayoutManager layoutManager;

FirebaseDatabase database;
DatabaseReference requests;

FirebaseRecyclerAdapter<Request, OrderViewHolder> adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_new_orders);

    //Firebase
    database = FirebaseDatabase.getInstance();
    requests = database.getReference("Order_Header");

    recyclerView = findViewById(R.id.listOrders);
    recyclerView.setHasFixedSize(true);
    layoutManager = new LinearLayoutManager(this);
    recyclerView.setLayoutManager(layoutManager);

    adapter = new FirebaseRecyclerAdapter<Request, OrderViewHolder>(
            Request.class,
            R.layout.order_layout,
            OrderViewHolder.class,
            requests.orderByChild("fs_ID")
                    .equalTo("FS02")
    ) {
        @Override
        protected void populateViewHolder(OrderViewHolder viewHolder, Request model, int position) {
            viewHolder.txtOrderID.setText(adapter.getRef(position).getKey());
            viewHolder.txtOrderStatus.setText(convertCodeToStatus(model.getStatus()));
            viewHolder.txtOrderUsername.setText(model.getUsername());
            viewHolder.txtOrderFname.setText(model.getFirstName());
            viewHolder.txtOrderLname.setText(model.getLastName());
            viewHolder.txtOrderEmail.setText(model.getEmail());
            viewHolder.txtOrderAddress.setText(model.getAddress());
        }
    };
    recyclerView.setAdapter(adapter);
}

private String convertCodeToStatus(String status){
    //pasok db how

    if (status.equals("OS1")) {
        return "Placed";
    }
    else if (status.equals("OS2")) {
        return "In progress";
    }
    else {
        return "OS3";
    }
}

}

应该显示的屏幕为空,这可能是什么问题?谢谢

1 个答案:

答案 0 :(得分:1)

您似乎没有在任何地方调用startListening,这是FirebaseUI开始观察数据库所必需的。现在,您告诉adapter要观察哪些数据以及如何处理数据,但从未告诉过它开始这样做。

您通常会希望在活动的onStart中开始收听,然后在onStop()中停止收听。

@Override
protected void onStart() {
    super.onStart();
    adapter.startListening();
}

@Override
protected void onStop() {
    super.onStop();
    adapter.stopListening();
}

另请参阅FirebaseUI documentation on the adapter lifecycle