【问题标题】:Android, cannot resolve a var in an objectAndroid,无法解析对象中的 var
【发布时间】:2021-08-11 13:20:37
【问题描述】:

所以我很确定这是我对 Java var 生命周期如何工作的想法,但仍然如此。

所以我有两个变量,name 和 pfpPath。在对象中,我获得了一个 uuid,从那里,我需要前往 Firebase 并在考虑到 uuid 的情况下提取数据并将其放入变量中。 问题是在 completeListener 内部,变量无法被识别。

我该如何解决这个问题?

代码:

package com.example.create4me;

import androidx.annotation.NonNull;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;

public class ChatItem {
    FirebaseFirestore db = FirebaseFirestore.getInstance();
    String name, pfpPath, userID;
    public ChatItem(String userID){
        this.userID = userID;
        db.collection("users")
                .whereEqualTo("uuid", this.userID)
                .get()
                .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<QuerySnapshot> task) {
                        if(task.isSuccessful()){
                            for(QueryDocumentSnapshot doc : task.getResult()){
                                this.name = doc.get("username");        <---THIS
                                this.pfpPath = doc.get("profilePic");   <---AND THIS
                            }
                        }
                    }
                });
    }
    public String getName(){
        return this.name;
    }
    public String getPfpPath(){
        return this.pfpPath;
    }
    public String getUserID(){
        return this.userID;
    }
}

错误:

【问题讨论】:

    标签: java android firebase google-cloud-firestore


    【解决方案1】:

    this 指的是您的 OnCompleteListener anon 内部类实例,而不是封闭的 ChatItem 实例。要引用它,您可以将this 的范围限定为ChatItem.this。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-20
      • 1970-01-01
      • 2023-02-05
      • 2013-04-23
      • 2015-01-25
      • 1970-01-01
      相关资源
      最近更新 更多