等待 Cloud Firestore 任务结果

huangapple go评论67阅读模式
英文:

Wait for Cloud Firestore task result

问题

我正试图开发一种方法来访问 Cloud Firestore,读取用户数据并返回与之关联的映射。据我理解,它没有等待成功/失败监听器,我已经尝试将其更改为完全监听器,但结果是相同的。它跳过了这些监听器。
我知道这是一个异步过程,但我需要接收数据以在调用该方法的 Activity 中显示它们。

Settings Activity:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.binding = ActivitySettingsBinding.inflate(getLayoutInflater());
        this.fbUtils = new FirebaseHandler(this);
        setContentView(binding.getRoot());
    }

    @Override
    protected void onStart() {
        super.onStart();
        User user = fbUtils.getCurrentUser();
        if (user == null) {
            findUserOrLogout();
        } else {
            showUserData(user);
        }
    }

FirebaseHandler:

    public User getCurrentUser() {
        FirebaseUser user = auth.getCurrentUser();
        if (user != null) {
            this.userMap = getUserDBInfo(user.getUid());
            this.profilePic = getUserPic(user.getUid());
            if (this.userMap != null && this.profilePic != null) {
                return new User(user, userMap, profilePic);
            }
        }
        return null;
    }
    
    private Map<String, Object> getUserDBInfo(String uid) {
        Log.d(TAG, "Getting user info for user '" + uid + "'");
        DocumentReference docRef = db.collection("users").document(uid);
        final Map<String, Object>[] userMap = new Map[]{null};
        final boolean[] done = new boolean[]{false};
        docRef.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
            @Override
            public void onSuccess(DocumentSnapshot documentSnapshot) {
                if (documentSnapshot.exists()) {
                    Log.d(TAG, "DocShot: " + documentSnapshot);
                    userMap[0] = documentSnapshot.getData();
                } else {
                    Log.d(TAG, "User's document not found");
                }
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Log.d(TAG, "Couldn't get the Document");
                MainActivity.showToast("Couldn't get the Document", activity.getApplicationContext());
            }
        });
        return userMap[0];
    }

我在代码中做错了什么,还是有什么可以改变的地方使其工作起来?
提前感谢。

英文:

I'm trying to develop a method to access the Cloud Firestore, read a user's data and return the map associated to it. For what I understand, it is not waiting for the success/failure listener, and I already tried changing it for a complete listener but the result is the same. It skips through the listeners.
I know that this is a Assynchronous process, but I need to receive the data to show them on the Activity that calls the method.

Settings Activity:

    @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.binding = ActivitySettingsBinding.inflate(getLayoutInflater());
this.fbUtils = new FirebaseHandler(this);
setContentView(binding.getRoot());
}
@Override
protected void onStart() {
super.onStart();
User user = fbUtils.getCurrentUser();
if (user == null) {
findUserOrLogout();
} else {
showUserData(user);
}
}

FirebaseHandler

    public User getCurrentUser() {
FirebaseUser user = auth.getCurrentUser();
if (user != null) {
this.userMap = getUserDBInfo(user.getUid());
this.profilePic = getUserPic(user.getUid());
if (this.userMap != null &amp;&amp; this.profilePic != null) {
return new User(user, userMap, profilePic);
}
}
return null;
}
private Map&lt;String, Object&gt; getUserDBInfo(String uid) {
Log.d(TAG, &quot;Getting user info for user &#39;&quot; + uid+&quot;&#39;&quot;);
DocumentReference docRef = db.collection(&quot;users&quot;).document(uid);
final Map&lt;String, Object&gt;[] userMap = new Map[]{null};
final boolean[] done = new boolean[]{false};
docRef.get().addOnSuccessListener(new OnSuccessListener&lt;DocumentSnapshot&gt;() {
@Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
if (documentSnapshot.exists()) {
Log.d(TAG, &quot;DocShot: &quot; + documentSnapshot);
userMap[0] = documentSnapshot.getData();
} else {
Log.d(TAG, &quot;User&#39;s document not found&quot;);
}
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.d(TAG, &quot;Couldn&#39;t get the Document&quot;);
MainActivity.showToast(&quot;Couldn&#39;t get the Document&quot;, activity.getApplicationContext());
}
});
return userMap[0];
}

Am I doing something wrong in my code, or is there anything I can change to make this work?

Thanks in advance.

答案1

得分: 1

你必须在Firebase控制台内更改规则,以允许写入操作。

您需要按照以下步骤进行操作:

  1. 打开Firebase控制台,进入Database(数据库)。

  2. 在那里转到**Rules(规则)**选项卡,并编辑规则如下:

{
  "rules": {
    ".read": true,
    ".write": true
  }
}

这将允许您在数据库上执行写入操作。

如果您需要截屏,请告诉我。

英文:

You have to change the rules inside the Firebase console to allow a write operation.

You've to follow the steps given below to do so:-

  1. Open your Firebase Console and navigate to Database.

  2. There go to the Rules tab and edit the rules to following:-

{
&quot;rules&quot;: {
&quot;.read&quot;: true,
&quot;.write&quot;: true
}
}

This will allow you to perform write operations on your DB.

Please let me know if you will need screenshots.

答案2

得分: 0

如果您的数据库需要经过身份验证的用户才能读写数据库,请不要使用此处的其他答案。这将创建一个巨大的安全漏洞,允许任何拥有互联网连接的人完全读写数据库。

相反,您的代码应该在尝试进行任何查询之前确保用户已登录。这可以通过使用身份验证状态侦听器来实现,以便在用户登录时获得回调。只有在使用有效的用户对象调用此回调后,才能安全地进行需要身份验证的查询。

英文:

If your database requires an authenticated user to read and write the database then do use the other answer here. It will create a massive security hole that allows for anyone with an internet connection to fully read and write the database.

Your code should instead ensure that a user is signed in before trying to make any queries. This made possible by using an auth state listener to get a callback when the user is signed in. Only after this callback is invoked with a valid user object is it safe to make a query that requires authentication.

huangapple
  • 本文由 发表于 2020年8月15日 23:48:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/63427953.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定