Alfn William
Alfn William

Reputation: 27

Retrieve a single data from Firebase Realtime Database

I'm new to firebase and I wanted to store a high score and retrieve it from Firebase Realtime database. The storage is working as intended , but I couldn't find a tutorial to retrieve the stored data. The official documentation is a bit confusing for me. Kindly help me out.

public class result extends AppCompatActivity {

    TextView fscore,highs; Button pagain; String scor; int hs,scrcheck;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_result);
        fscore=(TextView)findViewById(R.id.finalscore);
        highs=(TextView)findViewById(R.id.his);
        pagain=(Button)findViewById(R.id.pagain);
        scor=getIntent().getStringExtra("score");
        fscore.setText(scor);

        // need code here to retrieve the existing highscore value from firebase and assign it to highs textview.



        //code to update highscore
        scrcheck=Integer.parseInt(scor);
        if(scrcheck>hs)
        {
            hs=scrcheck;
            FirebaseDatabase.getInstance().getReference().child("highscore").setValue(hs);

        }

        highs.setText(Integer.toString(hs));

    
}

This is my Firebase database .

Thanks in advance.

Upvotes: 0

Views: 207

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598817

Based on the documentation on getting values:

DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
ref.child("highscore").addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        System.out.println("highscore: " + dataSnapshot.getValue(Long.class));
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        throw databaseError.toException();
    }
}

Upvotes: 2

Related Questions