简体   繁体   中英

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.

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();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM