How to retrieve specific list of data from firebase
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);
...
}
...
}
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
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.