1

I have some code that will store the number of times a particular OS has been voted for on Firebase. I use the following to store it:

DatabaseReference windowsChoice;

And inside the onCreate method:

 FirebaseDatabase.getInstance().getReference("Windows");

Inside the button method I store the data to firebase with:

String id = "TimesClicked";
windowsChoice.child(id).setValue(b); //b holds the amount of times that Windows has been clicked

The resulting format is such:

{"Windows":{"TimesClicked":8},"choice1Num":23} // ignore choice1Num

The following code will get me the value of Windows (TimesClicked:8):

String result = new Connector().execute().get();
JSONObject ob = new JSONObject(result);
String jsonString = ob.getString("Windows");

String id = "TimesClicked";
windowsChoice.child(id).setValue(b); 

intent.putExtra("result", jsonString);
startActivity(intent);

But how can I get the value of the TimesClicked label?

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
Ben
  • 129
  • 9

1 Answers1

0

But how can I get the value of the TimesClicked label?

Simply, by using the following lines of code:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference timesClickedRef = rootRef.child("Windows").child("TimesClicked");
ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        long timesClicked = dataSnapshot.getValue(Long.class);
        Log.d("TAG", "timesClicked: " + timesClicked);
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
        Log.d("TAG", databaseError.getMessage()); //Don't ignore errors!
    }
};
timesClickedRef.addListenerForSingleValueEvent(valueEventListener);

The result in the logcat will be:

timesClicked: 8
Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
  • How can I access the timesClicked outside of the OnDataChange if its declared inside the method? – Ben May 22 '20 at 11:13
  • You can only use it there or you can pass it to another method. This is because Firebase APIs are asynchronous. There is a workaround for that, in which you can use a [custom callback](https://stackoverflow.com/questions/47847694/how-to-return-datasnapshot-value-as-a-result-of-a-method/47853774). – Alex Mamo May 22 '20 at 11:20