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

Firebase Database报错:无法将String转换为long,读取经纬度数据失败

问题根因

报错Failed to convert a value of type java.lang.String to long的核心触发原因有两个:

  1. 实体类MapAdapter中定义的latitude、longitude字段为Long类型,但Firebase Realtime Database的Locations节点下存储的经纬度是字符串格式,类型不匹配导致Firebase序列化数据时无法完成自动转换。
  2. onCreate方法中存在多余的无效代码mUsers.push().setValue(marker);,会直接往Locations节点写入空的Marker对象,导致读取时数据结构异常。

修复步骤

  • 删除onCreate方法中的mUsers.push().setValue(marker);代码,该操作无业务意义且会写入垃圾数据。
  • 修复onMapReady方法中的语法错误,将googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE;补充右括号改为googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);。
  • 修正MapAdapter类的字段类型,匹配数据库存储格式。经纬度本身包含小数,不适合用Long类型存储,推荐选择以下两种方案之一:
    方案一:与数据库存储的字符串类型匹配,字段改为String类型:
    public class MapAdapter {
         public String latitude,longitude;
    
        public MapAdapter() {
    
        }
    
        public String getLatitude() {
            return latitude;
        }
    
        public void setLatitude(String latitude) {
            this.latitude = latitude;
        }
    
        public String getLongitude() {
            return longitude;
        }
    
        public void setLongitude(String longitude) {
            this.longitude = longitude;
        }
    }
    
    对应修改数据读取逻辑,将字符串转成Double构造LatLng:
    @Override
    public void onDataChange(@NonNull DataSnapshot snapshot) {
        if(snapshot.exists()) {
            for (DataSnapshot dataSnapshot:snapshot.getChildren()) {
                MapAdapter mapAdapter = dataSnapshot.getValue(MapAdapter.class);
                double lat = Double.parseDouble(mapAdapter.latitude);
                double lng = Double.parseDouble(mapAdapter.longitude);
                LatLng location = new LatLng(lat, lng);
                mMap.addMarker(new MarkerOptions().position(location)).setIcon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW));
            }
        }
    }
    
    方案二:将数据库中存储的经纬度改为数值格式,实体类字段对应改为Double类型:
    public class MapAdapter {
         public Double latitude,longitude;
    
        public MapAdapter() {
    
        }
    
        public Double getLatitude() {
            return latitude;
        }
    
        public void setLatitude(Double latitude) {
            this.latitude = latitude;
        }
    
        public Double getLongitude() {
            return longitude;
        }
    
        public void setLongitude(Double longitude) {
            this.longitude = longitude;
        }
    }
    
  • 进入Firebase Realtime Database控制台,删除Locations节点下之前写入的无效Marker数据,保证所有子节点仅包含latitude、longitude两个属性,类型与实体类定义一致。

内容的提问来源于stack exchange,提问作者christos fiakkou

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 21:27:03