英文:
Retrieve a single data from Firebase Realtime Database
问题
我对Firebase还不太了解,我想要将高分存储并从Firebase实时数据库中检索出来。存储部分按预期进行,但我找不到有关检索存储数据的教程。官方文档对我来说有点混淆。请帮我解决一下。
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);
// 需要在这里编写代码,从 Firebase 检索现有的高分值,并将其赋值给 highs 文本视图。
// 用于更新高分的代码
scrcheck = Integer.parseInt(scor);
if (scrcheck > hs) {
hs = scrcheck;
FirebaseDatabase.getInstance().getReference().child("highscore").setValue(hs);
}
highs.setText(Integer.toString(hs));
}
}
这是我的Firebase数据库截图。
提前谢谢。
英文:
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.
答案1
得分: 2
根据获取值部分的文档:
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();
}
});
英文:
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();
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论