19

I am new to firebase and nosql database

I am trying to retrieve some specific data from a Firebase. I have a node universities and that node has many unique identifier as node which has so more data into it. I want to retrieve name from each node.

Please have a look at this.

enter image description here

What I have tried so far: I tried using addChildEventListener but this only listens first child. I've debugged it and it was only showing the values of the first child of universities node.

myRef.addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String s) {
            List<University> university = new ArrayList<>();
            Map<String, Object> td = (HashMap<String, Object>) dataSnapshot.getValue();

            Log.d("TAG",dataSnapshot.getValue().toString());
        }

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

        }
    });

I have also tried addValueEventListener. This listens the whole node and return whole data, but I am unable to extract "name" for it since it contains unique identifiers.

Please guide me into the right directions.

myRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                University university = dataSnapshot.getValue(University.class);
                List<University> universities = (List<University>) dataSnapshot.getValue(University.class);
                *//*List<String> lst = new ArrayList<String>();

            for(DataSnapshot dsp : dataSnapshot.getChildren()){
                lst.add(dsp.getKey());
            }
            Log.d("TAG",lst.toString());*//*

            Map<String, Object> td = (HashMap<String, Object>) dataSnapshot.getValue();


            *//*List<Object> values = new ArrayList<Object>(td.values());
            List<String> list=new ArrayList<String>();
            for(int i=0; i<values.size(); i++){
                list.add((String) values.get(i));
            }*//*
            Log.d("TAG", university.toString());
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
RubioRic
  • 2,442
  • 4
  • 28
  • 35
Zeeshan Shabbir
  • 6,704
  • 4
  • 38
  • 74

5 Answers5

36

If you using addValueEventListener for retrieve all university from Firebase

List<University> universityList = new ArrayList<>();
myRef.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot snapshot) {
        universityList.clear();
        for (DataSnapshot postSnapshot: snapshot.getChildren()) {
            University university = postSnapshot.getValue(University.class);
            universityList.add(university);

            // here you can access to name property like university.name

        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        System.out.println("The read failed: " + firebaseError.getMessage());
    }
});

Or if you using addChildEventListener

List<University> universityList = new ArrayList<>();
myRef.addChildEventListener(new ChildEventListener() {
    @Override
    public void onChildAdded(DataSnapshot dataSnapshot, String s) {
         University university = dataSnapshot.getValue(University.class);
         universityList.add(university);
         Log.i(TAG,"add university name = " + university.name);
         ...
    }
    ...
}
Community
  • 1
  • 1
Linh
  • 57,942
  • 23
  • 262
  • 279
  • ok i used the first one method. That method. Store hashMap type data into list. I mean it has total 3 index now. And each index contains HashMap kind of data. And i want to get name out of it. how would i do it? – Zeeshan Shabbir Jul 29 '16 at 07:00
  • I see the way use using in your post is different. in my code (in one method) , inside the for loop you will get the Univerty object, and use can access to name property by university.name – Linh Jul 29 '16 at 07:05
  • thank you it's working for me. keep going – Bipin Bharti May 10 '23 at 19:12
3

Regarding Linh's answer about using the addEventListener method. You can use GenericTypeIndicator in order to directly create the list of objects you'll be needing. Here's a quick example:

List<University> universityList = new ArrayList<>();
myRef.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot snapshot) {
        GenericTypeIndicator<List<University>> t = new GenericTypeIndicator<List<University>>() {};
        universityList = snapshot.getValue(t);
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        System.out.println("The read failed: " + firebaseError.getMessage());
    }
});

Hope this answer helps.

Robert
  • 31
  • 1
  • By using this method, make sure the data you upload is exactly a single List object by `setValue()`, not by `.push().setValue()`, otherwise you would get this exception: `Expected a List while deserializing, but got a class java.util.HashMap` – Sam Chen May 06 '20 at 16:51
2

You can use equalTo() of Query in which you can pass your custom string to match with firebase database.

like this way you can create your Query and set listener with that

Query queryRef = myFirebaseRef.orderByChild("name").equalTo("some name");

refer this thread for more.

Here is nice example from firebase officials, refer that and you will get clear idea

Community
  • 1
  • 1
Ravi
  • 34,851
  • 21
  • 122
  • 183
0
   public void onDataChange(DataSnapshot dataSnapshot) {
           for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
               User user = postSnapshot.getValue(User.class);
               list.add(user);
           }
       }

class User

class User{

String name;

String phone;

public String getname() {
    return name;
}

public void setname(String name) {
    this.name = name;
}


public String getphone() {
    return phone;
}

public void setphone(String phone) {
    this.phone = phone;
}

List bind with class

List<User> list== new ArrayList <>();

100% it will work

Rahul sharma
  • 1,492
  • 12
  • 26
  • From Review: Hi, please don't answer just with source code. Try to provide a nice description about how your solution works. See: [How do I write a good answer?](https://stackoverflow.com/help/how-to-answer). Thanks – sɐunıɔןɐqɐp Jan 29 '19 at 07:31
0

I had the same problem .You can just change the access specifier i.e public to private in the Model class you problem will be solved

  • 1
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Feb 24 '23 at 13:26