[英]How to get data from a map field from Firebase Firestore?
我想檢索存儲為 Cloud Firestore 上的地圖字段的數據。
我想從“所有評論”字段中獲取“評論”作為字符串,以在 TextView 中顯示它。
我試過這個來添加數據
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();
}
});
假設“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
需要注意的幾點:
HashMap<String, Object>
類型的對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.