【问题标题】:DataSnapshot getValue() in Firebase returns nullFirebase 中的 DataSnapshot getValue() 返回 null
【发布时间】:2018-12-11 04:31:49
【问题描述】:

我的主要活动的 onCreate() 方法中的一个例程是与 Firebase 数据库通信以执行以下三件事之一: 1) 如果用户是回访用户,请更新他们在 Firebase 上使用 SharedPreferences 在本地存储的所有首选项。 2) 如果用户是新用户并且没有数据存储在云端(他们从未下载过应用程序),则什么也不做。 3) 如果用户是新用户,但在其唯一的 Facebook 个人资料 ID 下存储了偏好,请下载他们的偏好并将其应用到 SharedPreferences 实例。

我一定错过了一些关于 DataSnapshot 工作原理的关键(可能是基本的)见解,因为我无法让我的以下代码工作:

    private void initializeFirebase(){
    my_db = FirebaseDatabase.getInstance();
    DatabaseReference my_ref = my_db.getReference();

    Map<String, ?> values = sharedPreferences.getAll();

    if (values.isEmpty()){
        final String id = Profile.getCurrentProfile().getId();
        my_ref = my_ref.child("userid");
        my_ref.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                if (dataSnapshot.getKey().equals(id)){
                    data = (Map<String, Object>)dataSnapshot.getValue();
                }
            }

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

            }
        });
    }
    else {
        for (Map.Entry<String, ?> entry : values.entrySet()) {
            my_ref.child("userid").child(Profile.getCurrentProfile().
                    getId()).child(entry.getKey()).setValue(entry);
        }
    }
}

data 是一个全局 Map 变量,在执行 getValue() 后始终为 null。

我的 JSON 树组织为:root -> users -> userid -> 每个首选项作为 userid 节点的子节点。任何帮助将不胜感激!

【问题讨论】:

  • 请更具体。您是说 DataSnapshot 本身为空吗?还是它的 getValue() 返回 null?问题的症状是什么?
  • 另外,您确定要在这里使用字符串“userid”吗? my_ref.child("userid")
  • 抱歉——getValue 返回空值。名为“数据”的地图始终为空。我相信是的。

标签: android firebase firebase-realtime-database


【解决方案1】:

根据getValue() 的 API 文档,它可以返回 null:

此快照中包含的数据作为本机类型,如果此位置没有数据,则为 null。

所以,您查询的位置没有数据。

我猜你不想在你的引用中硬编码一个“userid”的值。我敢打赌,您的意思是使用上一行中的用户 ID:

final String id = Profile.getCurrentProfile().getId();
my_ref = my_ref.child(id);  // id instead of "userid"

【讨论】:

  • 你是对的!哎呀...我觉得这很愚蠢,哈哈。
  • 如果您不介意将此答案标记为正确,我将不胜感激。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-21
  • 1970-01-01
相关资源
最近更新 更多