我正在尝试更改本教程的private void displayListView()
(http://www.mysamplecode.com/2012/07/android-listview-custom-layout-filter.html),以便在我从mySql数据库获取数据时检查它是否仍然有效。
这是我的PHP文件中的Json数组:
[{"code":"AFG","name":"Afghanistan","continent":"Asia","region":"Southern and Central Asia"}, {"code":"ALB","name":"Albania","continent":"Europe","region":"Southern Europe"},{"code":"DZA","name":"Algeria","continent":"Africa","region":"Northern Africa"},{"code":"ASM","name":"American Samoa","continent":"Oceania","region":"Polynesia"},{"code":"AND","name":"Andorra","continent":"Europe","region":"Southern Europe"},{"code":"AGO","name":"Angola","continent":"Africa","region":"Central Africa"},{"code":"AIA","name":"Anguilla","continent":"North America","region":"Caribbean"}]
这就是我的所作所为:
private void displayListView() {
// Creating volley request obj
JsonArrayRequest stringRequest = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Country country = new Country(code, name, continent, region);
country.setCode(obj.getString("code"));
country.setName(obj.getString("name"));
country.setContinent(obj.getString("continent"));
country.setRegion(obj.getString("region"));
// adding country to country array
countryList.add(country);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this,error.getMessage(),Toast.LENGTH_LONG).show();
}
});
RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
queue.add(stringRequest);
但是我收到了一个错误:
java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
我不确定我是否以正确的方式解析JSON,我无法弄清楚错误。任何帮助将不胜感激。
答案 0 :(得分:0)
这是因为你没有从你的应用程序中获取任何来自php的数据。尝试从服务调用中记录您收到的结果,然后传递进行解析。