字符串转Double失败:TextView经纬度转数值报错求助
解决TextView字符串转Double失败的问题
常见问题原因
- TextView中的字符串包含非数字字符(如空格、逗号代替小数点、多余符号、中文标点等)
- 字符串为空或仅含空白字符
- 经纬度格式不符合Double类型要求(概率较低)
解决方案
1. 清理字符串并处理格式
转换前先去除空白字符,替换可能的非法分隔符:
String latitudeStr = textViewLatt.getText().toString().trim(); String longitudeStr = textViewLong.getText().toString().trim(); // 若使用逗号作为小数点,替换为标准小数点 latitudeStr = latitudeStr.replace(",", "."); longitudeStr = longitudeStr.replace(",", ".");
2. 添加异常捕获与调试
捕获转换时的NumberFormatException,同时打印日志排查问题:
double latt = 0.0; double longi = 0.0; try { latt = Double.parseDouble(latitudeStr); longi = Double.parseDouble(longitudeStr); // 执行地图定位逻辑 LatLng target = new LatLng(latt, longi); mMap.addMarker(new MarkerOptions().position(target).title("Marker")); mMap.moveCamera(CameraUpdateFactory.newLatLng(target)); } catch (NumberFormatException e) { // 打印错误日志,查看具体异常字符串 e.printStackTrace(); // 提示用户格式错误 Toast.makeText(this, "经纬度格式无效", Toast.LENGTH_SHORT).show(); }
3. 排查TextView实际内容
通过日志输出TextView的原始字符串,确认是否有隐藏字符:
Log.d("LatLngDebug", "纬度原始值:'" + latitudeStr + "'"); Log.d("LatLngDebug", "经度原始值:'" + longitudeStr + "'");
查看Logcat中的输出,就能明确字符串是否存在异常(如换行符、不可见空格等)。
4. 直接从Firebase读取Double类型
跳过字符串中转环节,直接从Firebase读取Double值,避免转换问题:
databaseReference.child("location").addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { Double latitude = dataSnapshot.child("latitude").getValue(Double.class); Double longitude = dataSnapshot.child("longitude").getValue(Double.class); if (latitude != null && longitude != null) { // 直接使用Double值定位 LatLng target = new LatLng(latitude, longitude); mMap.addMarker(new MarkerOptions().position(target).title("Marker")); mMap.moveCamera(CameraUpdateFactory.newLatLng(target)); // 更新TextView显示 textViewLatt.setText(String.valueOf(latitude)); textViewLong.setText(String.valueOf(longitude)); } } @Override public void onCancelled(DatabaseError databaseError) { // 处理数据库读取错误 } });
内容的提问来源于stack exchange,提问作者Timow
相关产品推荐
相关产品推荐

