Store Value of Key to Global Variable Firebase Android ‘pathString’ in child()

I’m trying to store the value of ds.getKey() to the global variable Common.workerType so that whenever I need to get a value from the database, I wouldn’t have to repeat these set of codes over and over again, more ideally just to make it like this

final DatabaseReference dbRefChild = dbRef.child(Common.user_workers_table).child(Common.workerType).child(Common.uid);

I know that the error is showing because it’s getting a null data, but how come? I believe I got the right path of the nodes. This is the error I’m getting:

java.lang.NullPointerException: Can't pass null for argument 'pathString' in child()

    final DatabaseReference newRef = FirebaseDatabase.getInstance().getReference();
    final DatabaseReference newRefChild = newRef.child(Common.user_workers_table);

    newRefChild.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for(DataSnapshot ds: dataSnapshot.getChildren()) {
                if(ds.child(Common.uid).exists()) {
                    Common.workerType = ds.getKey();
                }
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

Here’s how the database looks like:

Common.user_workers_table refers to Workers

Common.workerType refers to Plumbers

Answer

You cannot declare Common.workerType as o global variable and simply use it outside the onDataChange() method because it will always be null. This is happening because this method has an asynchronous behaviour, which means that is called even before you are getting the data from the database.

Even if this would have been possible, as I see in your code, you are looping through the entire dataSnapshot object using getChildren() method and every value that you get you assign it to the same variable. In this case, you variable will always have the value of last iteration.

A quick solve for the first problem would be, to use the value of Common.workerType only inside the onDataChange() method or if you need it outside, dive into the asynchronous world and see the last part of my anwser from this post. You can also take a look at this video for a better understanding.

Leave a Reply

Your email address will not be published. Required fields are marked *