Firebase检索/读取返回空值 - Android

时间:2016-04-01 15:59:26

标签: android json firebase firebase-realtime-database

使用Firebase文档检索数据:

ref.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot snapshot) {
        System.out.println(snapshot.getValue());
    }
    @Override
    public void onCancelled(FirebaseError firebaseError) {
        System.out.println("The read failed: " + firebaseError.getMessage());
    }
}); 

运行以上产生的:

  

{users = {facebook:############### = {posts = { - KE8qg1VyPAwYj0uJDcn = {status = update1}},provider = facebook,displayName = Some Name}}}

创建用于表示用户的类:

@JsonIgnoreProperties(ignoreUnknown=true) //to ignore mapping issues
public class Users {

String status;
String displayName;
String provider;

public Users() {
        // empty default constructor
}

public String getStatus() {
    return status;
}

public String getName(){
    return displayName;
}

public String getProvider(){
    return provider;
}
}

使用以下内容尝试检索值:

ref.addChildEventListener(new ChildEventListener() {
        // Retrieve new posts as they are added to the database
        @Override
        public void onChildAdded(DataSnapshot snapshot, String previousChildKey) {
            Users newUser = snapshot.getValue(Users.class);
            System.out.println("Status: " + newUser.getStatus());
            System.out.println("Display Name: " + newUser.getName());
            System.out.println("Provider: " + newUser.getProvider());
        }

一切都返回null?阅读&尝试了几个使用for循环迭代数据库的例子,但那些也失败了所以我决定回到第一个版本。不确定哪种方式最适合这种情况?

1 个答案:

答案 0 :(得分:1)

现在返回数据。实现到底会有太多的嵌套,所以现在帖子在一个单独的节点中。更改了代码:

final Firebase userRef = rootRef.child("users/" + rootRef.getAuth().getUid());

为:

final Firebase userRef = rootRef.child("posts");