0

I am reading some data from Firebase's real-time database. I want to read the data and then display it in a recycleView. When I enter debug mode it is reading the data and saving it to a local variable, but for some reason, it is returning null when it is being call by the recycleView adapter. I have some data that I am also writing as well and that is working, so I know the firebase database is connecting.

My Homeblinds class (where the connection to firebase is made and receiving the data)

public class HomeBlinds {
DatabaseReference ref;
String temp,light,blindkey,location;

// this will house data on the specific blind.
public HomeBlinds(String test,String blindkey) {
    this.blindkey = blindkey;
    ref = FirebaseDatabase.getInstance().getReference(blindkey);
}
public String getLocation() {
    ref.child("Location").addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {
            String l = String.valueOf(snapshot.getValue());
            location = l;
        }
        @Override
        public void onCancelled(@NonNull DatabaseError error) {
        }
    });
    return location;
}

My recycleView adapter class

 @Override
public void onBindViewHolder(@NonNull HomeViewHolder holder, int position) {
    HomeBlinds x = testblinds.get(position);
    String location = x.getLocation();
    holder.loc.setText("Location: "+String.valueOf(x.getLocation()));

    holder.temp.setText("Temperature: "+String.valueOf(x.getTemperature()));

    holder.light.setText("Light: "+String.valueOf(x.getLight()));

Photo of the Firebase real-time database

Firebase database

Current output

output

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Amit Punit
  • 21
  • 2
  • If you set breakpoints and run the code in a debugger, you'll see that your `return location` runs before the `location = l` is ever reached. That is because data is loaded from Firebase (and most cloud APIs) asynchronously, and your main code continues to execute. For this reason, any code that needs the data from the database needs to be inside the `onDataChange` method, be called from there, or be otherwise synchronized. See the question I linked for more on this. – Frank van Puffelen Jul 20 '22 at 03:43
  • 1
    You are calling the data for specific not a list. You must use `foreach` loop inside the `onDataChange` – Ticherhaz FreePalestine Jul 20 '22 at 03:44
  • Check [this question](https://stackoverflow.com/questions/57330766/why-does-my-function-that-calls-an-api-or-launches-a-coroutine-return-an-empty-o) for some more information – Tyler V Jul 20 '22 at 04:27
  • I think that this [resource](https://medium.com/firebase-tips-tricks/how-to-read-data-from-firebase-realtime-database-using-get-269ef3e179c5) might help. – Alex Mamo Jul 20 '22 at 05:53

0 Answers0