Java.lang.ClassCastException: java.util.HashMap cannot be cast to com.kornerz.kornerz.Communities
I'm trying to convert the data that comes from firebase to a list, in order to list a recyclerview It turns out that when I try to pull this data to the communites class to supply the recyclerview, the conversion gives an error.
My Collection it's like this
This is the class 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;
}
}
this is part of code i need convert and populate the array list
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);
}
}
}
});
CodePudding user response:
I think you're looking for the DocumentSnapshot.toObject(Class<T> valueType))
method, which can convert the data to an object of a specific class - as long as the data and class follow the same naming conventions.
In your code that'd look like this:
documentSnapshot.toObject(Communities.class)
Note though that the field names in your document don't follow the JavaBean naming pattern that Firestore SDK expects, so you will either have to rename the fields (e.g. communityId
instead of community_id
) or add PropertyName
annotations in the code of the Communities
class to tell the SDK how to map the values between the code and database.