简体   繁体   中英

How to retrieve all values of a particular key in Firebase real time database?

 public void getFirstName(View view) {
    Query newQuery = database.getReference("users").orderByChild("firstName");
    newQuery.addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String s) {
            Iterable<DataSnapshot> iterator = dataSnapshot.getChildren();
            for (DataSnapshot child : iterator) {
               Friends friends = child.getValue(Friends.class);
                Toast.makeText(DBActivity.this, friends.firstName, Toast.LENGTH_SHORT).show();
            }
        }

        @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) {

        }
    });
}

JSON文件结构

I am trying to retrieve the first names of all friends. When I try the above code for the mentioned JSON file structure, I am getting this error "Can't convert object of type java.lang.String to type com.example.seth.photopicker.Friends". Please help me with this issue.

Try this:

Query newQuery = database.getReference("users");
newQuery.addChildEventListener(new ChildEventListener() {
    @Override
    public void onChildAdded(DataSnapshot dataSnapshot, String s) {
           String fname=dataSnapshot.child("firstName").getValue().toString();
            Toast.makeText(DBActivity.this, friends.firstName, Toast.LENGTH_SHORT).show();
        }
    }

The datasnapshot is at users and since you are using onChildAdded you do not need to iterate to be able to get the first name.

  Query newQuery = database.getReference("users").orderByChild("firstName");
    newQuery.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
                Friends friends = dataSnapshot1.getValue(Friends.class);
                Toast.makeText(DBActivity.this, friends.firstName, Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

Equivalent code for above answer without using Child Listener.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM