Android JSONArray到ArrayList
我正在尝试在我的Android应用程序中将JSONArray解析为和ArrayList。PHP脚本正确地重新调整了预期的结果,但是Java失败并在以下位置出现了空指针异常resultsList.add(map)
public void agencySearch(String tsearch) { // Setting the URL for the Search by Town
String url_search_agency = "http://www.infinitycodeservices.com/get_agency_by_city.php";
// Building parameters for the search
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("City", tsearch));
// Getting JSON string from URL
JSONArray json = jParser.getJSONFromUrl(url_search_agency, params);
for (int i = 0; i < json.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
try {
JSONObject c = (JSONObject) json.get(i);
//Fill map
Iterator iter = c.keys();
while(iter.hasNext()) {
String currentKey = (String) iter.next();
map.put(currentKey, c.getString(currentKey));
}
resultsList.add(map);
}
catch (JSONException e) {
e.printStackTrace();
}
};
MainActivity.setResultsList(resultsList);
}
回答:
尝试这样可能会帮助您,
public void agencySearch(String tsearch) { // Setting the URL for the Search by Town
String url_search_agency = "http://www.infinitycodeservices.com/get_agency_by_city.php";
// Building parameters for the search
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("City", tsearch));
// Getting JSON string from URL
JSONArray json = jParser.getJSONFromUrl(url_search_agency, params);
ArrayList<HashMap<String, String>> resultsList = new ArrayList<HashMap<String, String>>();
for (int i = 0; i < json.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
try {
JSONObject c = json.getJSONObject(position);
//Fill map
Iterator<String> iter = c.keys();
while(iter.hasNext()) {
String currentKey = it.next();
map.put(currentKey, c.getString(currentKey));
}
resultsList.add(map);
}
catch (JSONException e) {
e.printStackTrace();
}
};
MainActivity.setResultsList(resultsList);
}
以上是 Android JSONArray到ArrayList 的全部内容, 来源链接: utcz.com/qa/416491.html