Android Studio中数据库经纬度字符串转Double适配Google Maps Fragment
解决字符串经纬度转Double适配Google Maps的问题
Got it, let's sort this out—you need to turn those string-based latitude and longitude values from your database into Double types so Google Maps can use them, right? Here's a straightforward, safe way to do it, including error handling to prevent crashes from bad data.
Step-by-Step Implementation
First, let's adjust your existing Cursor loop to extract, convert, and use the coordinates properly:
Cursor res = dbHelper3.getEvent(journey, message); if (res.getCount() == 0) { showMessageData("Error", "No data"); return; } // 可选:创建列表存储转换后的坐标,方便后续批量处理 List<LatLng> eventLocations = new ArrayList<>(); while (res.moveToNext()) { // 从Cursor中获取字符串格式的经纬度(替换成你的实际列名) String latString = res.getString(res.getColumnIndex("lat")); // 注意:如果数据库列名是"long",会和Java关键字冲突,建议改成"longitude" String lngString = res.getString(res.getColumnIndex("longitude")); Double latitude = null; Double longitude = null; // 安全转换,处理可能的格式错误 try { latitude = Double.parseDouble(latString.trim()); // 先trim避免前后空格导致转换失败 longitude = Double.parseDouble(lngString.trim()); } catch (NumberFormatException e) { // 记录错误日志,或者根据需求提示用户 Log.e("LocationConvert", "Invalid lat/long data: " + e.getMessage()); continue; // 跳过这条无效数据,或者做其他处理 } // 转换成功后,创建Google Maps需要的LatLng对象 if (latitude != null && longitude != null) { LatLng eventLocation = new LatLng(latitude, longitude); eventLocations.add(eventLocation); // 直接在地图上添加标记(如果mMap是你的GoogleMap实例) mMap.addMarker(new MarkerOptions() .position(eventLocation) .title("Event Location")); } } // 关闭Cursor避免内存泄漏 res.close();
Key Notes to Avoid Issues
- Column Name Best Practice: If your longitude column is named
long, rename it tolongitudein your database—longis a Java keyword, and using it can cause confusion or syntax warnings. - Trim Whitespace: Always call
.trim()on the string before parsing—extra spaces at the start/end of your stored values will causeNumberFormatException. - Error Handling: Never skip catching
NumberFormatException—if your database has invalid non-numeric values, this will prevent your app from crashing and let you log the problem. - Cursor Cleanup: Don't forget to close the Cursor after processing to avoid memory leaks.
内容的提问来源于stack exchange,提问作者D.Grosso
相关产品推荐
相关产品推荐

