将Android Firebase中的所有孩子检索到RecyclerView

时间:2017-06-21 19:41:12

标签: android firebase firebase-realtime-database

有人可以帮我解决这段代码吗?问题是我只收到我数据库中的最后一项。

    FirebaseDatabase.getInstance().setPersistenceEnabled(true);
    DatabaseReference database = FirebaseDatabase.getInstance().getReference();
    database.child("Ministries").addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for(DataSnapshot child : dataSnapshot.getChildren()) {

                String min = child.child("Ministry").getValue().toString();
                min_address = child.child("Address").getValue().toString();
                min_tel = child.child("Tel").getValue().toString();
                min_fax = child.child("Fax").getValue().toString();
                min_email = child.child("e_mail").getValue().toString();
                min_website = child.child("website").getValue().toString();

                final RecyclerView rv = (RecyclerView) findViewById(id.recycler_view);
                rv.setHasFixedSize(true);
                LinearLayoutManager llm = new LinearLayoutManager(getApplicationContext());
                rv.setLayoutManager(llm);
                List<Ministries> m = new ArrayList<>();
                m.add(new Ministries(min, min_address, min_tel, min_fax, min_email, min_website, R.drawable.ic_ministries));
                RVAdapter adapter = new RVAdapter(m);
                rv.setAdapter(adapter);

            }
        }
        @Override
        public void onCancelled(DatabaseError databaseError) {}
    });

1 个答案:

答案 0 :(得分:1)

您需要在for循环之外移动列表创建和RecyclerView逻辑。

例如:

    public void onDataChange(DataSnapshot dataSnapshot) {

        List<Ministries> m = new ArrayList<>();

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

            String min = child.child("Ministry").getValue().toString();
            min_address = child.child("Address").getValue().toString();
            min_tel = child.child("Tel").getValue().toString();
            min_fax = child.child("Fax").getValue().toString();
            min_email = child.child("e_mail").getValue().toString();
            min_website = child.child("website").getValue().toString();

            m.add(new Ministries(min, min_address, min_tel, min_fax, min_email, min_website, R.drawable.ic_ministries));

        } 

        final RecyclerView rv = (RecyclerView) findViewById(id.recycler_view);
        rv.setHasFixedSize(true);
        LinearLayoutManager llm = new LinearLayoutManager(getApplicationContext());
        rv.setLayoutManager(llm);

        RVAdapter adapter = new RVAdapter(m);
        rv.setAdapter(adapter);

    }