地图绘制两点路线时应用崩溃求助(附代码与报错日志)
咱们先定位问题根源:从报错日志能看到,空指针出现在ParserTask.onPostExecute的第238行——你直接调用result.size()时,result是null。这是因为解析JSON数据时出了问题,doInBackground返回了null,但后续代码没做空值判断。下面一步步解决:
1. 先堵住空指针的直接漏洞
在ParserTask.onPostExecute方法最开头添加空值判断,避免直接操作null对象:
@Override protected void onPostExecute(List<List<HashMap<String, String>>> result) { // 新增:先检查result是否为空 if (result == null) { Toast.makeText(getApplicationContext(), "获取路线失败,请检查网络或API配置", Toast.LENGTH_LONG).show(); return; } ArrayList<LatLng> points = null; PolylineOptions lineOptions = null; // 原遍历代码保持不变 for(int i=0;i<result.size();i++){ // ... 原代码 } // ... 原代码 }
2. 排查解析失败的深层原因
result为null通常是因为下载的JSON无效,或者API调用出了问题,咱们从这几个方向检查:
(1)检查Manifest配置是否完整
这是最容易踩的坑,确保AndroidManifest.xml包含以下内容:
- 网络权限(必须,要调用Google Directions API):
<uses-permission android:name="android.permission.INTERNET" />
- 定位权限(可选但建议加,方便后续扩展):
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
- Google Maps API Key配置(放在
<application>标签内):
<meta-data android:name="com.google.android.geo.API_KEY" android:value="@string/google_maps_key" />
关键提醒:去Google Cloud Console确认你已经启用了Directions API,并且API Key没有被错误限制(比如IP、应用签名配置不对)。
(2)修复下载方法的潜在bug
你的downloadUrl方法的finally块有风险:如果网络请求失败,iStream没初始化,调用iStream.close()会抛异常,导致下载失败。修改成这样:
finally{ if (iStream != null) { try { iStream.close(); } catch (IOException e) { e.printStackTrace(); } } if (urlConnection != null) { urlConnection.disconnect(); } }
(3)增强JSON解析的容错性
在DirectionsJSONParser.parse方法里,先检查API返回的status字段,只有状态为OK时才继续解析,避免解析错误的JSON:
public List<List<HashMap<String,String>>> parse(JSONObject jObject){ List<List<HashMap<String, String>>> routes = new ArrayList<>() ; JSONArray jRoutes = null; JSONArray jLegs = null; JSONArray jSteps = null; try { // 新增:先检查API返回状态 String status = jObject.getString("status"); if (!"OK".equals(status)) { Log.e("DirectionsAPI", "API错误状态: " + status); return routes; // 返回空列表,避免后续解析崩溃 } jRoutes = jObject.getJSONArray("routes"); // 原解析代码保持不变 } catch (JSONException e) { e.printStackTrace(); Log.e("JSON解析错误", e.getMessage()); }catch (Exception e){ Log.e("解析异常", e.getMessage()); } return routes; }
3. 调试查看API返回内容
在DownloadTask.doInBackground里打印下载的JSON数据,能直观看到API返回的是有效路线还是错误信息:
@Override protected String doInBackground(String... url) { String data = ""; try{ data = downloadUrl(url[0]); Log.d("DownloadTask", "API返回数据: " + data); // 新增日志 }catch(Exception e){ Log.d("Background Task",e.toString()); } return data; }
如果日志显示status为REQUEST_DENIED,那就是API Key的问题,去Google Cloud Console检查配置即可。
按照这些步骤修改后,空指针问题应该能解决,同时也能排查出API调用的潜在问题。
内容的提问来源于stack exchange,提问作者Ica

