如何从Firebase数据库中获取Android列表视图中的用户名列表?

时间:2017-02-07 11:03:02

标签: android listview firebase firebase-realtime-database

我已通过我的应用注册并保存了用户,现在我想从Firebase数据库中获取如下所示的用户名列表。我如何在列表视图中执行此操作?我的数据库如下所示:

1

3 个答案:

答案 0 :(得分:1)

获取数据库参考

firebaseDatabase = FirebaseDatabase.getInstance();
mPostDb = firebaseDatabase.getReference("User");

现在查询你的表

Query query = mPostDb.orderByKey();
    query.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for(DataSnapShot user : dataSnapshot){
                // Do what ever you whatever you want with this user object 
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

答案 1 :(得分:1)

ArrayList<MODELCLASSNAME> Users=new ArrayList<>();
DatabaseReference df=FirebaseDatabase.getInstance().getReference().child("users");
df.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapShot user : dataSnapshot.getchildren()){

          Users.add(dataSnapshot.getValue(MODELCLASSNAME.class));

      }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {

    }
});
//Now loop through your arraylist

答案 2 :(得分:0)

试试这个方法:

public void retrieveNames() {

    Query myQuery = mDatabase.orderByChild("name").equalTo("INSERT-HERE-A-NAME-FOR-YOUR-SEARCH");

    myQuery.addChildEventListener(new ChildEventListener() {

        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String s) {

            Iterator iterator = dataSnapshot.getChildren().iterator();
//FOR YOUR DATA STRUCTURE -
   while (iterator.hasNext()) {
                String image_uri = (String) ((DataSnapshot) iterator.next()).getValue();
                String name = (String) ((DataSnapshot) iterator.next()).getValue();
                String username = (String) ((DataSnapshot) iterator.next()).getValue();
                YourUserObject User = new YourUserObject  (image_uri, name, username);

                YourArrayList.add(User);

            }
            YourAdapter.notifyDataSetChanged();
        }

            @Override
        public void onChildChanged(DataSnapshot dataSnapshot, String s) {
        }
        @Override
        public void onChildRemoved(DataSnapshot dataSnapshot) {
        }
        @Override
        public void onChildMoved(DataSnapshot dataSnapshot, String s) {
        }
        @Override
        public void onCancelled(DatabaseError databaseError) {
        }
    });
}