Nouman Tahir Nouman Tahir - 1 month ago 17
Android Question

firebase - get single object from list as snapshot

So I have a list of objects stored in firebase and want to query for just one object using child equal to method but I am getting a map with single key value instead.

Code below showing what I want to achieve instead of dealing with hashmaps.

final FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference coutryRef = database.getReference(FireContract.PATH_COUNTRY);

Query countryQuery = coutryRef.orderByChild(FireContract.CHILD_NAME)
.equalTo(TestUtilities.TEST_COUNTRY_ALGERIA).limitToFirst(1);

countryQuery.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {

Country country = dataSnapshot.getValue(Country.class);
assertEquals(TestUtilities.TEST_COUNTRY_ALGERIA, country.getName());

//get country key
String coutryKey = dataSnapshot.getKey();
}

@Override
public void onCancelled(DatabaseError databaseError) {
fail("Failed to get country: " + databaseError.getMessage());

}
});

Answer

When you fire a query, you will always get a list of results. Even when there is only a single item matching the query, the result will be a list of one item.

To handle the list, you can either use a ChildEvenListener or you can loop over the children in your ValueEventListener:

countryQuery.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot countrySnapshot: dataSnapshot.getChildren()) {

            Country country = countrySnapshot.getValue(Country.class);
            assertEquals(TestUtilities.TEST_COUNTRY_ALGERIA, country.getName());

            //get country key
            String countryKey = countrySnapshot.getKey(); 
        }  
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        fail("Failed to get country: " + databaseError.getMessage());
    }
});