robbiestells
robbiestells

Reputation: 275

Android Firebase Database query returning null

I'm trying to query a Firebase Database but keep getting null returned. Here is what the database looks like:

enter image description here

And the Stem object:

public class Stem {
    private String stem;

    public Stem(){}

    public Stem(String stem){
        this.stem = stem;
    }

    public String getText(){
        return stem;
    }

    public void setText(String stem){
        this.stem = stem;
    }
}

And the MainActivity in the OnCreate

mFirebaseDatabase = FirebaseDatabase.getInstance();
mStemDatabaseReference = mFirebaseDatabase.getReference().child("Stems");

 getStemButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

if (mChildEventListener == null) {
                    mChildEventListener = new ChildEventListener() {
                        @Override
                        public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                            Stem stem = dataSnapshot.getValue(Stem.class);
                            mStemAdapter.add(stem);
                        }

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

                        }
                    };
                    mStemDatabaseReference.addChildEventListener(mChildEventListener);
                }

            }
        });

The query seems to access the database fine because it returns the Stems json array, but when it tries to add the stem to the adapter it returns stem as null. Any ideas?

Upvotes: 0

Views: 1498

Answers (3)

chris williams
chris williams

Reputation: 13

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...
}

Upvotes: 0

SuperHaker
SuperHaker

Reputation: 178

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.

Upvotes: 2

Wilik
Wilik

Reputation: 7720

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

    }
});

Upvotes: 1

Related Questions