0

I really hope, you can help me here:

I'm trying to create a Class "Cloud" where all the Firestore-Stuff is happening.

But I can't overwrite Attributes with Firestore Values and work with them in my Main-Activity. It will always give me a Null-Object-Reference-Error.

Example

Inside my Cloud-Class I have an Attribute "theTest". With the Method "Test()" I now want to overwrite this Attribute with a Value of my Firestore Database:

   public String Test(){
    db.collection("Products").whereEqualTo("isAvailable", true).get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
        @Override
        public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
            theTest = queryDocumentSnapshots.getDocuments().get(0).getId();
        }
    });
    return theTest;
}

Now in my Main-Activity, I want to use this value just like:

String test = cloud.Test();
Log.d("TheTest", test);

But it's not working! I always get the same Null Object Reference Error.

I don't know what exactly I'm doing wrong..

Thank you in Advance!

1 Answers1

0

The reason you get the null value is that retrieving data from Firebase is an async function. So, it won't fetch your value and then proceed to return. It will first return theTest which is null at that point and then go back to the onSuccess when it's done.

You need to somehow work inside your onSuccess method, so you'll need to wait for your query to finish in order to get theTest value and not the null value. This answer explains how to wait for Firebase to fetch data and then proceed.

But as suggested in the answer in that question:

Don't use Firebase as functions that return values - it goes against it's asynchronous nature.

Plan code structure that allows Firebase to perform it's task and then within the closure (block) go to the next step.

In your code, for example, change the function to not return anything and within the onDataChange, as the last line call the next function to update your UI.

Try to implement a different approach to get this value.

SlothCoding
  • 1,546
  • 7
  • 14