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

从Firebase Realtime Database获取用户位置出现NPE该如何修复?

问题根源
  • 路径引用错误:你代码中构造的数据库路径为/Users/User Location,但你数据库里User Location是和Users平级的根节点,同时User Location下还有一层用户UID节点,你直接读取latitude相当于访问不存在的字段,返回null值,后续LatLng构造时拆箱Double为基础类型double就触发了空指针。
修复方案

首先修正数据库路径,补充用户UID层级,同时增加非空校验避免崩溃。
修复后的代码如下:

@Override
public void onMapReady(@NonNull GoogleMap googleMap) {
    mMap = googleMap;
    // 修正路径:直接指向根节点下的User Location,再拼接用户UID
    // 若读取当前登录用户的位置,可替换为FirebaseAuth.getInstance().getCurrentUser().getUid()
    String targetUid = "RCX2HZXIwlSmMHFgDytf1DgZBgi2";
    DatabaseReference locationRef = FirebaseDatabase.getInstance().getReference("User Location").child(targetUid);

    locationRef.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
        @Override
        public void onComplete(@NonNull Task<DataSnapshot> task) {
            if (task.isSuccessful()) {
                DataSnapshot snapshot = task.getResult();
                // 先判断节点是否存在,再取值加非空校验
                if (snapshot.exists()) {
                    Double latitude = snapshot.child("latitude").getValue(Double.class);
                    Double longitude = snapshot.child("longitude").getValue(Double.class);
                    if (latitude != null && longitude != null) {
                        LatLng location = new LatLng(latitude, longitude);
                        mMap.addMarker(new MarkerOptions().position(location).title(getCompleteAddress(latitude, longitude)));
                        mMap.moveCamera(CameraUpdateFactory.newLatLng(location));
                        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(location,14F));
                        Log.d("TAG", "latitude: " + latitude + ", longitude: " + longitude);
                    } else {
                        Log.d("TAG", "经纬度字段为空");
                    }
                } else {
                    Log.d("TAG", "对应用户的位置数据不存在");
                }
            } else {
                Log.d("TAG", "读取失败: " + task.getException().getMessage());
            }
        }
    });
}

内容的提问来源于stack exchange,提问作者Rafael Campos

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 12:15:01