如何从Firebase检索所有数据并将其放在RecyclerView上

时间:2016-09-19 10:03:19

标签: android firebase firebase-realtime-database android-recyclerview firebaseui

这是我的数据库结构enter image description here

我想检索孩子Passenger中的所有数据,并将其放在RecyclerView内......怎么可能?

2 个答案:

答案 0 :(得分:1)

您可以使用FirebaseUI for Android库。

只需添加依赖项(0.5.3适用于firebase 9.4.0库):

DatabaseReference

定义FirebaseDatabase database = FirebaseDatabase.getInstance(); DatabaseReference ref = database.getReference("passengers");

ViewHolder

然后:

  • 创建自定义FirebaseRecyclerAdapter
  • 创建自定义子类ViewHolder

public static class PassengerHolder extends RecyclerView.ViewHolder { } 类:

FirebaseRecyclerAdapter

RecyclerView recycler = (RecyclerView) findViewById(R.id.messages_recycler); recycler.setHasFixedSize(true); recycler.setLayoutManager(new LinearLayoutManager(this)); mAdapter = new FirebaseRecyclerAdapter<Passenger, PassengerHolder>(Passenger.class, R.layout.mylayout, PassengerHolder.class, mRef) { @Override public void populateViewHolder(PassengerHolder passengerViewHolder, Passenger passenger, int position) { passengerViewHolder.setName(passenger.getName()); //....... } }; recycler.setAdapter(mAdapter); 类:

{{1}}

答案 1 :(得分:1)

您可以尝试这样:

     FirebaseDatabase database = FirebaseDatabase.getInstance();
        DatabaseReference ref = database.getReference();

        ref.addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                   //Your Logic here
                    for (DataSnapshot eventSnapshot : dataSnapshot.getChildren()) {
                    YourModel mModel = eventSnapshot.getValue(YourModel.class);
                    Log.e("DATA" ,""+ mModel);   
                  }  
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });

您必须为Recycleview创建一个数组列表,并将每个模型mModel添加到您的arraylist并显示在列表中

More Info 1