You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Firestore查询报HashMap无法强转Communities类类型转换异常

报错信息
Java.lang.ClassCastException: java.util.HashMap cannot be cast to com.kornerz.kornerz.Communities
问题背景

Android开发过程中,调用Firebase Firestore接口查询Rooms集合数据,期望将返回结果转换为Communities实体类列表填充RecyclerView,执行时触发上述类型转换异常。
Firestore中Rooms集合的数据结构如下:
Firestore集合结构截图

问题相关代码

自定义Communities实体类

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

    // 存在拼写错误:方法名漏写字母y,应为setCommunityName
    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()){                  
                     // 错误点:直接强转getData()返回值
                     Communities communityList = (Communities) documentSnapshot.getData();        
                     communities.add(communityList);                                              
                 }                                                                                
             }                                                                                    
         }                                                                                        
     });   
错误原因
  • 核心错误:documentSnapshot.getData()的返回值类型是Map<String, Object>,底层由HashMap实现,和自定义Communities类没有继承关系,直接强转必然抛出类型转换异常。
  • 实体类存在拼写错误:setCommunitName方法名拼写错误,会导致Firestore自动映射community_name字段时出现匹配失败问题。
修复方案
  1. 修正实体类问题:删除拼写错误的setCommunitName方法,保留正确命名的setCommunityName方法即可;Firestore序列化依赖实体类的无参构造,当前类未自定义带参构造时会默认生成无参构造,可正常使用。
  2. 替换类型转换逻辑:使用Firestore SDK自带的toObject()/toObjects()方法完成文档到自定义实体的映射,禁止手动强转getData()的返回结果。
  3. 数据加载完成后主动通知RecyclerView适配器刷新,避免列表不显示最新数据。

修复后的查询代码

communities = new ArrayList<>();
db.collection("Rooms").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { 
    @Override                                                                                
    public void onComplete(@NonNull Task<QuerySnapshot> task) {                              
        if(task.isSuccessful()){
            // 直接批量转换为Communities实体列表,无需手动循环
            communities = task.getResult().toObjects(Communities.class);
            // 通知适配器数据更新
            adapter.notifyDataSetChanged();
        } else {
            // 可在此处打印错误日志排查查询问题
            Log.e("FirestoreError", "Rooms集合查询失败", task.getException());
        }                                                                                    
    }                                                                                        
});

如果需要单独处理单个文档,也可以在循环中调用单条转换方法:

Communities community = documentSnapshot.toObject(Communities.class);

内容的提问来源于stack exchange,提问作者Gabriel Falieri

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.28 15:09:21