You need to enable JavaScript to run this app. Android端Firebase Firestore实时数据读取触发空指针异常问题
优惠活动
大模型
产品
解决方案
定价
更多

Android端Firebase Firestore实时数据读取触发空指针异常问题

问题根因

你遇到的空指针异常是Java自动拆箱导致的:
Firestore的DocumentSnapshot.get()方法在目标字段不存在、值为空时会返回null,你直接将返回的null强转成int/double这类基本类型时,Java会自动尝试对包装类(Integer/Double)执行拆箱操作,调用intValue()/doubleValue()方法,对null对象调用实例方法就会抛出你遇到的报错。
你打印value.getData()不会崩溃是因为该方法返回的是Map集合,null值可以作为普通键值对正常打印,不会触发拆箱逻辑。

解决方案

1. 先校验字段匹配性

先确认Firestore对应文档的字段名和你strings.xml中定义的train_id、latitude、longitude、passenger_count的拼写、大小写完全一致,字段名不匹配会导致拿不到值返回null。

2. 使用安全取值+判空逻辑

不要直接强转成基本类型,改用Firestore提供的类型安全取值方法,取值后先判空再赋值,也可以按需设置默认值,修改后的onEvent逻辑如下:

@Override
public void onEvent(@Nullable DocumentSnapshot value, @Nullable FirebaseFirestoreException error) {
    if(error != null){
        Log.e(TAG,error.getMessage());
        error.printStackTrace();
        return; // 出现异常直接返回,避免后续逻辑执行
    }

    if(value != null && value.exists()){
        // 使用Firestore自带的类型方法取值,返回包装类避免直接拆箱
        Integer trainId = value.getInteger(getResources().getString(R.string.train_id));
        Double lat = value.getDouble(getResources().getString(R.string.latitude));
        Double lon = value.getDouble(getResources().getString(R.string.longitude));
        Integer passengerCount = value.getInteger(getResources().getString(R.string.passenger_count));

        // 判空后赋值,可根据业务需求设置默认值
        if(trainId != null) {
            trainInfoDTO.setTrainId(trainId);
        } else {
            Log.w(TAG, "trainId字段为空,可设置默认值或者做异常处理");
        }
        if(lat != null) {
            trainInfoDTO.setLat(lat);
        }
        if(lon != null) {
            trainInfoDTO.setLon(lon);
        }
        if(passengerCount != null) {
            trainInfoDTO.setPassengerCount(passengerCount);
        }
        // 额外补充train对象和seatingCapacity的判空,避免此处隐藏空指针风险
        if(train != null && train.getSeatingCapacity() != null) {
            trainInfoDTO.setSeatingCapacity(train.getSeatingCapacity());
        }
        System.out.println(value.getData());
    } else {
        showSnackbar(getResources().getString(R.string.no_train_data));
    }
}

内容的提问来源于stack exchange,提问作者M.Rishdhi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 05:45:04