Android Firebase Database Query Returning Null
Solution 1:
This is due to Firebase using asynchronous calls to access your database. As there is no OnComplete listener for this, you should notify your adapter for changes in the list. I was using RecyclerView when I faced this and just called notifyDataSetChanged
on the adapter to update it with the fetched values.
Solution 2:
Looks like the value under Stems
in your database is recognized as an array instead of an object. It is because the key for the stems is an incrementing number.
You can try to do Export JSON from the Firebase Database console and see the structure of your database. The value you will get should be like this:
{
"Stems": [
null,
{ "stem": "Test for stem 1"},
{ "stem": "Test for stem 2"}
]
}
You can read more about Firebase behavior with Arrays here
The solution for your problem is to use databaseReference.push()
method to generate the key for the new stem. With the push()
method, you don't have to remember the last key for the stem to increment it by 1. This push()
method is also recommended by Firebase as the way to add new child item.
Example of push()
method usage:
// create new Stem object
Stem stem = new Stem("Test for new stem");
// push new key under 'Stems' and then set the Stem object as value under the new key
mStemDatabaseReference.push().setValue(stem);
Hope this helps :)
EDIT: If you don't want to change your database structure
mStemDatabaseReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
GenericTypeIndicator<List<Stem>> genericTypeIndicator = new GenericTypeIndicator<List<Stem>>() {};
List<Stem> stemList = dataSnapshot.getValue(genericTypeIndicator);
for (Stem stem : stemList) {
if (stem != null) {
mStemAdapter.add(stem);
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
Solution 3:
Try moving the Firebase Query to a point later in the Activity load. I had a similar issue when passing values via Intent, but the data wasn't returned from Firebase in time to load into the variables before the intent was executed. Maybe you should create an initialization function and call that at the bottom of On Create.
init(){
...your code...
}
Post a Comment for "Android Firebase Database Query Returning Null"