从Firebase数据库检索特定数据 [英] Retrieving specific data from Firebase Database

查看:107
本文介绍了从Firebase数据库检索特定数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Firebase数据库和Java在android上创建聊天应用程序.每当用户首次注册时,它将用户名存储到节点user/UserID/profile/username下的数据库中.用户名使用User类存储.这是存储用户名值的位置.但是,当我尝试类似

I'm creating a chat app on android using Firebase Database and Java. Whenever the user is first registered, it stores their username into the database under the nodes user/UserID/profile/username. The username is stored using a User class. This is where the username value is stored. However when I try something like

mDatabase.child("users").child(UserID).child("profile").child("username").toString();

这给了我用户名的路径,但没有用户名本身的路径.有人知道如何获取用户名本身的值吗?

This gives me the path to the username but not the username itself. Does anybody know how to get the value of the username itself?

运行时它给我一个错误

DataSnapshot.child("users").child(mUserID).child("profile").child("username").getValue().toString();

这是我的Firebase数据库在用户ID下显示的内容.

Here is what my Firebase database shows under the UserID.

推荐答案

您没有正确获得该值.您需要为孩子附加一个侦听器并获取更新.您是这样做的:

You aren't getting the value properly. You need to attach a listener to you child and get updates. You do that like this:

// Get a reference to your user
final FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference ref = database.getReference("server/path/to/profile");

// Attach a listener to read the data at your profile reference
ref.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        Profile profile = dataSnapshot.getValue(Profile.class);
        System.out.println(profile.getUsername());
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        System.out.println("The read failed: " + databaseError.getCode());
    }
});

您可以在Firebase 网站上找到更多信息和示例.请记住,您不会发出从Firebase获取数据的请求.您将侦听器附加到孩子,然后从侦听器获取数据.本示例假定您有一个Profile模型,该模型具有一种用于获取用户名的方法.这将返回您的Profile对象,并使您能够从该对象获取所需的任何数据.

You can find more information and examples on the Firebase website. Keep in mind that you don't make requests to get data from Firebase. You attach listeners to the children and then get the data from the listener. This example assumes that you have a Profile model, with a method to get the username. This would return your Profile object and would enable you to get whatever data you need off of that object.

这篇关于从Firebase数据库检索特定数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆