如何从Firebase Firestore获取地图字段的数据?

发布于 2025-02-10 18:01:38 字数 3240 浏览 1 评论 0原文

我想检索存储的数据作为云firestore上的地图字段。
我想将“评论”作为“所有注释”字段的字符串中的字符串,以在文本视图中显示。

我该怎么做? (Java)

我尝试添加数据,

                Map<String,String> allComments=new HashMap<String,String>();
                String commentContent=commentboxedittext.getText().toString();
                allComments.put("Movie Name",name);
                allComments.put("Comment",commentContent);
                firebaseFirestore.collection("All Comments").document("MovieComments").set(allComments, SetOptions.merge());  

并且以检索数据,

DocumentReference docRef = firebaseFirestore.collection("All Comments").document("MovieComments");
                docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                        if (task.isSuccessful()) {
                            DocumentSnapshot document = task.getResult();
                            if (document.exists()) {
                                Map<String, Object> m=document.getData();
                                userComment=m.get("Comment").toString();
                                mName=m.get("Movie Name").toString();
                            } else {
                                Toast.makeText(MovieDetails.this, "No Such Document", Toast.LENGTH_SHORT).show();
                            }
                        } else {
                            Toast.makeText(MovieDetails.this, "Error", Toast.LENGTH_SHORT).show();
                        }
                    }
                });  

但是应用程序会崩溃。
我还尝试这样做以放置数据并起作用,但后来我不知道如何检索数据表。

            Map<String,String> allComments=new HashMap<String,String>();
            Map<String, Object> user=new HashMap<String,Object>();
        userID=firebaseAuth.getCurrentUser().getUid();
        userReference=firebaseFirestore.collection("Users ").document(userID);
            String commentContent=commentboxedittext.getText().toString();
            allComments.put("Movie Name",name);
            allComments.put("Comment",commentContent);
            user.put("All Comments",allComments);
            userReference.set(user, SetOptions.merge()).addOnSuccessListener(new OnSuccessListener<Void>() {
                @Override
                public void onSuccess(Void unused) {
                    Toast.makeText(MovieDetails.this, "Comment Added", Toast.LENGTH_SHORT).show();
                }
            }).addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    if(e instanceof FirebaseNetworkException)
                        Toast.makeText(MovieDetails.this, "No Internet Connection", Toast.LENGTH_SHORT).show();
                    Toast.makeText(MovieDetails.this, "Values Not Stored", Toast.LENGTH_SHORT).show();
                }
            });

I want to retrieve data stored as a map field on Cloud Firestore.
I want to get the 'Comment' as a string from 'All Comments' field to show it in a TextView.

How can I do it? (Java)
enter image description here

I tried this to add the data

                Map<String,String> allComments=new HashMap<String,String>();
                String commentContent=commentboxedittext.getText().toString();
                allComments.put("Movie Name",name);
                allComments.put("Comment",commentContent);
                firebaseFirestore.collection("All Comments").document("MovieComments").set(allComments, SetOptions.merge());  

And this to retrieve the data

DocumentReference docRef = firebaseFirestore.collection("All Comments").document("MovieComments");
                docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                        if (task.isSuccessful()) {
                            DocumentSnapshot document = task.getResult();
                            if (document.exists()) {
                                Map<String, Object> m=document.getData();
                                userComment=m.get("Comment").toString();
                                mName=m.get("Movie Name").toString();
                            } else {
                                Toast.makeText(MovieDetails.this, "No Such Document", Toast.LENGTH_SHORT).show();
                            }
                        } else {
                            Toast.makeText(MovieDetails.this, "Error", Toast.LENGTH_SHORT).show();
                        }
                    }
                });  

But app crashes on doing this.
I also tried doing this to put the data and it worked but then I do not know how to retrieve data form this method.

            Map<String,String> allComments=new HashMap<String,String>();
            Map<String, Object> user=new HashMap<String,Object>();
        userID=firebaseAuth.getCurrentUser().getUid();
        userReference=firebaseFirestore.collection("Users ").document(userID);
            String commentContent=commentboxedittext.getText().toString();
            allComments.put("Movie Name",name);
            allComments.put("Comment",commentContent);
            user.put("All Comments",allComments);
            userReference.set(user, SetOptions.merge()).addOnSuccessListener(new OnSuccessListener<Void>() {
                @Override
                public void onSuccess(Void unused) {
                    Toast.makeText(MovieDetails.this, "Comment Added", Toast.LENGTH_SHORT).show();
                }
            }).addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    if(e instanceof FirebaseNetworkException)
                        Toast.makeText(MovieDetails.this, "No Internet Connection", Toast.LENGTH_SHORT).show();
                    Toast.makeText(MovieDetails.this, "Values Not Stored", Toast.LENGTH_SHORT).show();
                }
            });

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

终遇你 2025-02-17 18:01:38

假设“ l4ir ... xy12”是身份验证的用户的ID,以获取“所有注释”映射中存在的“注释”的值,请使用以下代码行:

String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
FirebaseFirestore db = FirebaseFirestore.getInstance();
db.collection("users").document(uid).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<DocumentSnapshot> task) {
        if (task.isSuccessful()) {
            DocumentSnapshot document = task.getResult();
            if (document.exists()) {
                String comment = ((HashMap<String, Object>) document.getData().get("All Comments")).get("Comment").toString();
                Log.d("TAG", comment);
            } else {
                Log.d("TAG", "No such document");
            }
        } else {
            Log.d("TAG", "get failed with ", task.getException());
        }
    }
});

logcat中的结果将为:

sfgs

要注意的几件事:

Assuming that "l4ir...Xy12" is ID of the authenticated user, to get the value of the "Comment" that exists within the "All Comments" map, please use the following lines of code:

String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
FirebaseFirestore db = FirebaseFirestore.getInstance();
db.collection("users").document(uid).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<DocumentSnapshot> task) {
        if (task.isSuccessful()) {
            DocumentSnapshot document = task.getResult();
            if (document.exists()) {
                String comment = ((HashMap<String, Object>) document.getData().get("All Comments")).get("Comment").toString();
                Log.d("TAG", comment);
            } else {
                Log.d("TAG", "No such document");
            }
        } else {
            Log.d("TAG", "get failed with ", task.getException());
        }
    }
});

The result in the logcat will be:

sfgs

A few things to note:

  • DocumentSnapshot#get(String field) returns an object of type Object. Since each field inside a document represents a pair of keys and values, we can cast the result to an object of type HashMap<String, Object>.
  • Since we already have a Map, we can get the call Map#get(Object key) method, which returns the value associated with the key.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文