简体   繁体   中英

How to get data from a map field from Firebase Firestore?

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) 在此处输入图像描述

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();
                }
            });

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM