我的项目从api获取公交车票时间信息。但是,如果没有来自服务器的返回时间数据,则不会显示运行时间。这是我通过Volley发送请求时的错误消息。
错误json.JSONException:索引1超出范围[0..1)
代码段
private void sendRequest(final String owner, final Map<String, String> header) {
StringRequest stringRequest = new StringRequest(Request.Method.POST, MyConstants.URL + owner,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// Log.e("AAAA" + owner, response);
try {
JSONObject object = new JSONObject(response);
if (object.getString(MyConstants.SERVICE_STATUS).equals(MyConstants.SERVICE_RESPONSE_STATUS_NOTAVAILABLE)) {
// servisten gelen cevap not_available ise
//// owner
sendVoyagesErrorBroadcast(owner, MyConstants.ERROR_NOTAVAILABLE);
} else if (object.getString(MyConstants.SERVICE_STATUS).equals(MyConstants.SERVICE_RESPONSE_STATUS_SUCCESS)) {
JSONArray result = object.getJSONArray(MyConstants.SERVICE_RESULT);
JSONArray resultGoing = result.getJSONObject(0).getJSONArray("going");
if (has_return) {
JSONArray resultReturn = result.getJSONObject(1).getJSONArray("round");
sendVoyagesArrayBroadcast(owner + MyConstants.DIRECTION_RETURN, resultReturn);
}
sendVoyagesArrayBroadcast(owner + MyConstants.DIRECTION_GOING, resultGoing);
} else if (object.getString(MyConstants.SERVICE_STATUS).equals(MyConstants.SERVICE_RESPONSE_STATUS_FAİLURE)) {
sendVoyagesErrorBroadcast(owner, MyConstants.ERROR_SERVER);
}
} catch (JSONException e) {
Log.e("search" + owner + "VoyagesErr1", e.toString());
e.printStackTrace();
}
}
答案 0 :(得分:1)
请检查以下代码
if (has_return) {
JSONArray resultReturn = result.getJSONObject(1).getJSONArray("round");
sendVoyagesArrayBroadcast(owner + MyConstants.DIRECTION_RETURN, resultReturn);
}
您正在尝试访问索引1处的元素,该元素可能不存在。索引从0而不是1开始,因此即使结果json数组的大小为1也会给出错误
尝试做这样的事情
if (has_return) {
if (result.length() > 1)
JSONArray resultReturn = result.getJSONObject(1).getJSONArray("round");
sendVoyagesArrayBroadcast(owner + MyConstants.DIRECTION_RETURN, resultReturn);
}
}
否则,如果您对第一个元素感兴趣,请像这样访问它
if (result.length() > 0) {
JSONArray resultReturn = result.getJSONObject(0).getJSONArray("round");
}