0

I have a RecyclerView that stores the adapter's list in my Firebase, and I am trying to get a specific node from that database but I am having some issues.

This is what I have right now to get the specific value at the node:

public double getWager(int position) {

    FCGames.child(openGames.get(position)).child("wager").addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            wagerr = (double) dataSnapshot.getValue();
            String wagerD = Double.toString(wagerr);

            wage = wagerD.endsWith("0");
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });
    return wagerr;
}

Now from what I remember, return statements don't work well with Firebase, but I don't see why this wouldn't work. I have 'wagerr' defined at the top of the class and this returns the value after it gets the value I am looking for.

And in my RecyclerView, I am trying to set this double as a setText so it can be drawn on the screen, but that is where my issue comes into play.

This is what I have calling on my getWager method:

holder.wager.setText(String.format(""+ fcl.getWager(position)));

But I get this error when I try to make it all work:

Attempt to invoke virtual method 'double com.example.brent.hidden-app.GameLobby.getWager(int)' on a null object reference

Is there a way to solve this issue, or is there a better way to grab that value from the node and use it elsewhere?

brent
  • 131
  • 12
  • 1
    Please check the duplicate to see why do you have this behaviour and how can you solve this using a custom callback. – Alex Mamo Nov 05 '18 at 07:47

1 Answers1

0

Since this call is asynchronous, I'd suggest adding a list (I'd suggest an ArrayList) in the adapter, and populate that list on the onChildAdded or onDataChange depending on the usage.

Then in getWager() you get the Wager from that arraylist. (eg: return list.get(position);)

Usman Rafi
  • 316
  • 1
  • 2
  • 12
  • Just for some clarification: I already have an ArrayList that stores all of the open games, and one of the variables within this list is the Wager that I am trying to get. So are you suggesting creating another list that stores the wagers separately and then assigns them to the correlated game? – brent Nov 05 '18 at 05:06