【问题标题】:Problem to retrieve data from firestore inside Listener从侦听器内的 firestore 检索数据的问题
【发布时间】:2021-02-04 21:13:14
【问题描述】:

我得到一个错误,我的监听器中的变量显示正确的值,但是当它离开时它只是一个空变量。

if (i.getStringExtra("where").equals("login")){
        email = i.getStringExtra("email");
        db.collection("users").whereEqualTo("email", email).get()
                .addOnCompleteListener(task -> {
                    if (task.isSuccessful()) {
                        for (DocumentSnapshot document : task.getResult()) {
                            name = document.getString("name");
                            Log.d("username", name);
                        }
                    }
                });
    }else{
        //anything
    }
    Log.d("username", name);
    userName.setText(name);

Listener 内部的 Log 返回正确的值,而外来者给出一个空指针 excpetion println 需要一条消息。 尝试使用 this.name 而不是 name,仍然无效。

更新

我在输入 if 条件之前给变量名称一个值,并注意 if 之外的 Log.d 首先打印旧值,然后 if 内部的 Log.d 打印正确的值:

2021-02-05 13:29:06.791 27900-27900/com.example.pomodorotasks D/用户名:teste

2021-02-05 13:29:09.020 27900-27900/com.example.pomodorotasks D/用户名:Rafael Alves

“teste”旧值 “Rafael Alves”名称在侦听器内部接收的值

听者做它需要做的似乎需要一些时间,我不知道。

【问题讨论】:

标签: firebase variables google-cloud-firestore


【解决方案1】:

已解决

此评论https://stackoverflow.com/a/42811962/15148029

不要将 Firebase 用作返回值的函数 - 这违背了它的异步特性。

规划允许 Firebase 执行其任务的代码结构,然后在闭包(块)内进行下一步。

例如,在您的代码中,将函数更改为不返回任何内容并在 onDataChange 内,因为最后一行调用下一个函数来更新您的 UI。


不知道异步函数的这个细节。

【讨论】:

  • 让我们避免错误的假设;虽然这个说法是正确的Don't use Firebase as functions that return values,问题中的代码doesn't do that,没有返回数据,所以这个答案不适用于您的问题。实际问题是闭包 Log.d("username", name); 之后的代码将在闭包中的代码之前运行,因此它在执行时似乎不会被填充。但是,一旦闭包中的代码运行,它就会被填充。在name = document.getString("name"); 之后移动该代码和此userName.setText(name); 将起作用。
猜你喜欢
  • 2019-07-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-28
  • 1970-01-01
  • 1970-01-01
  • 2018-11-15
相关资源
最近更新 更多