Java.lang.ClassCastException: java.util.HashMap cannot be cast to com.kornerz.kornerz.Communities
我正在嘗試將來自 firebase 的資料轉換為串列,以列出 recyclerview 事實證明,當我嘗試將此資料拉到 Communites 類以提供 recyclerview 時,轉換會出錯。
我的收藏是這樣的

這是類 Communities.Java
package com.kornerz.kornerz;
import com.google.firebase.firestore.GeoPoint;
public class Communities {
private String community_id,community_name, community_theme, community_number_members, community_distance;
private GeoPoint community_location;
public String getCommunityId() {
return community_id;
}
public void setCommunityId(String communityId) {
this.community_id = communityId;
}
public String getCommunityName() {
return community_name;
}
public void setCommunityName(String communityName) {
this.community_name = communityName;
}
public String getCommunityNumberMembers() {
return community_number_members;
}
public void setCommunityNumberMembers(String community_number_members) {
this.community_number_members = community_number_members;
}
public String getCommunityDistance() {
return community_distance;
}
public void setCommunityDistance(String community_distance) {
this.community_distance = community_distance;
}
public void setCommunitName(String community_name) {
this.community_name = community_name;
}
public String getCommunityTheme() {
return community_theme;
}
public void setCommunityTheme(String community_theme) {
this.community_theme = community_theme;
}
public GeoPoint getCommunityLocation() {
return community_location;
}
public void setCommunityLocation(GeoPoint community_location) {
this.community_location = community_location;
}
}
這是我需要轉換并填充陣列串列的代碼的一部分
communities = new ArrayList<>();
db.collection("Rooms").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if(task.isSuccessful()){
for(QueryDocumentSnapshot documentSnapshot : task.getResult()){
Communities communityList = (Communities) documentSnapshot.getData();
communities.add(communityList);
}
}
}
});
uj5u.com熱心網友回復:
我認為您正在尋找可以將資料轉換為特定類的物件的DocumentSnapshot.toObject(Class<T> valueType))方法- 只要資料和類遵循相同的命名約定。
在您的代碼中,如下所示:
documentSnapshot.toObject(Communities.class)
請注意,盡管檔案中的欄位名稱不遵循 Firestore SDK 所期望的 JavaBean 命名模式,因此您必須重命名欄位(例如communityId,而不是)或在類的代碼中community_id添加PropertyName注釋Communities以告訴 SDK 如何映射代碼和資料庫之間的值。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/497484.html
