如何获得最后两个节点?

时间:2018-09-17 10:02:23

标签: android firebase firebase-realtime-database

这是数据库结构

enter image description here

如何获取最后两个节点?

public class MainActivity extends AppCompatActivity {

public RecyclerView recyclerView , recyclerView1 ;




@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
        final DatabaseReference requestsRef = FirebaseDatabase.getInstance().getReference().child("Requests");
        recyclerView = (RecyclerView) findViewById(R.id.recycler_foods);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        Query firstRequestQuery = requestsRef.orderByKey().limitToFirst(1);
        firstRequestQuery.addValueEventListener(new ValueEventListener() {

            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

                for (DataSnapshot requestSnapshot: dataSnapshot.getChildren()){


                    FirebaseRecyclerAdapter<Food,FoodViewHolder> adapter = new FirebaseRecyclerAdapter<Food, FoodViewHolder>(
                            Food.class,
                            R.layout.individual_row,
                            FoodViewHolder.class,
                            requestSnapshot.getRef().child("foods")



                    ) {
                        @Override
                        protected void populateViewHolder(FoodViewHolder viewHolder, Food model, int position) {
                            viewHolder.setProductName(model.getProductName());
                            viewHolder.setQuantity(model.getQuantity());

                        }
                    };


                    recyclerView.setAdapter(adapter);
                }
            }
            @Override
            public void onCancelled(DatabaseError databaseError) {
            }

        });

1 个答案:

答案 0 :(得分:0)

您只需要正确使用DatabaseReference。您可以使用它们的名称和正确的FirebaseDatabase引用从数据库中访问所有节点。

我的意思是,在代码中看起来像这样:

DatbaseReference ref = FirebaseDatabase.getInstance().getReference().child("Requests").child(specialNumber).child("foods").child(0);

ref.addListenerForSingleValueEvent(new ValueEventListener() {
                    @Override
                    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                        for(DataSnapshot data: dataSnapshot.getChildren()){
                           int value = dataSnapshot.child("productId");
                            int value2 = dataSnapshot.child("quantity");

                        }
                    }

                    @Override
                    public void onCancelled(@NonNull DatabaseError databaseError) {

                    }
                });

此外,为避免投票不足,请在询问新问题之前搜索与您类似的问题。