java - org.json.JSONException: Index 0 out of range [0..0) 如何解决?
问题描述
在项目中添加谷歌地图 api 后,我从过去几天开始面临这个问题。我已经完成了一切,我启用了免费试用计费,并且还对代码进行了许多更改,但我什么也没得到,之后我添加了 google place api,但结果是搜索栏突然消失了。
在此代码中,它显示错误:
private void drawRoute(final LatLng yourLocation, String address) {
mService.getGeoCode(address).enqueue(new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
try{
JSONObject jsonObject=new JSONObject(response.body().toString());
String lat= ((JSONArray)jsonObject.get("results"))
.getJSONObject(0)
.getJSONObject("geometry")
.getJSONObject("location")
.get("lat").toString();
String lng= ((JSONArray)jsonObject.get("results"))
.getJSONObject(0)
.getJSONObject("geometry")
.getJSONObject("location")
.get("lng").toString();
LatLng orderLocation=new LatLng(Double.parseDouble(lat),Double.parseDouble(lng));
Bitmap bitmap= BitmapFactory.decodeResource(getResources(),R.drawable.locationmarker);
bitmap=Common.scaleBitmap(bitmap,70,70);
MarkerOptions marker=new MarkerOptions().icon(BitmapDescriptorFactory.fromBitmap(bitmap))
.title("Order of "+Common.currentRequest.getPhone())
.position(orderLocation);
mMap.addMarker(marker);
//draw route
mService.getDirections(yourLocation.latitude+","+yourLocation.longitude,
orderLocation.latitude+","+orderLocation.longitude)
.enqueue(new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
new ParserTask().execute(response.body().toString());
}
@Override
public void onFailure(Call<String> call, Throwable t) {
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Call<String> call, Throwable t) {
}
});
}
解决方案
我猜错误发生在这个地方:
((JSONArray)jsonObject.get("results"))
.getJSONObject(0)
您必须考虑该results
属性仅包含一个空数组的情况。为此,您可以将results
数组分配给一个变量,测试它的长度以及它是否0
执行其他操作,例如立即返回(什么都不做)或向用户显示消息。
JSONArray results = (JSONArray)jsonObject.get("results");
if (results.length() == 0) {
// handle this case, for example
return;
}
// There is at least one result
String lat= results
.getJSONObject(0)
.getJSONObject("geometry")
...
推荐阅读
- javascript - mac Safari javascript 全屏方法无法按预期工作
- python-3.x - 如何使 VSCode 自动建议、快速建议、函数签名表示和智能感知模仿 jupyter 行为?
- javascript - 字符串作为注释——性能有什么影响?
- svg - 有没有办法在单个 svg 中包含 2 个渐变(线性和径向)?[已回答/已解决]
- reactjs - 在 GCP 上存储 React+Gatsby 静态应用程序时管理处理程序
- python - 从 python 中的 yaml 文件中读取值并使用命令 api ssh 到具有该值的开关
- r - ggplot2 和 ggdist:跳过绘制 group 有 1 个 obs 的分布。在多个箱线图中
- node.js - 为什么我不能在 nodejs 和 mongodb 中多次发出 post 请求
- sql - 从每个标识符有多行的列表中选择第一行
- android - Firebase Crashlytics 导致我的统一游戏在初始屏幕上崩溃