简体   繁体   English

如何从 Firebase 数据库中读取数据? - 爪哇

[英]How to read data from Firebase Database? - Java

I'm making a game, if the player wins, then the victory is added to the database.我在做一个游戏,如果玩家获胜,那么胜利就会被添加到数据库中。 How can I read the data from here?我怎样才能从这里读取数据?

在此处输入图像描述

and paste here:并粘贴在这里:

在此处输入图像描述

I read the player's name in a different way, which cannot be repeated with victories and defeats.我以不同的方式读取玩家的名字,无法重复胜利和失败。

To be able to read the data under the jjjj node, please use the following lines of code:为了能够读取jjjj节点下的数据,请使用以下代码行:

DatabaseReference db = FirebaseDatabase.getInstance().getReference();
DatabaseReference nameRef = db.child("players").child("jjjj");
nameRef.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<DataSnapshot> task) {
        if (task.isSuccessful()) {
            DataSnapshot snapshot = task.getResult();
            String loses = snapshot.child("loses").getValue(Long.class);
            String name = snapshot.child("name").getValue(String.class);
            String wins = snapshot.child("wins").getValue(Long.class);
            Log.d("TAG", loses + "/" + name + "/" + wins);
        } else {
            Log.d("TAG", task.getException().getMessage()); //Never ignore potential errors!
        }
    }
});

The result in the logcat will be: logcat 中的结果将是:

3/jjjj/4

Things to notice:注意事项:

  • Always create a reference that points to the node that you want to read.始终创建指向要读取的节点的引用。
  • If your database is located in another lcoation than the default, check this answer out.如果您的数据库位于默认位置以外的其他位置,请检查此答案

use this method使用这个方法

This is the method of fetching data from the firebase realtime database这是从firebase实时数据库中获取数据的方法

DatabaseReference reference = FirebaseDatabase.getInstance().getReference();

    reference.child("players").child(name).addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {
            for (DataSnapshot dataSnapshot : snapshot.getChildren()){

            }
        }

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

        }
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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