我目前正在关注本教程(http://mobile.dzone.com/news/android-tutorial-how-parse)如何//将项目从 doddataitemObj 添加到数据项字符串 - String PUBLICEVENTTYPE = d.getString(PUBLICEVENTTYPE); 是说局部变量 PUBLICEVENTTYPE 可能没有被初始化。因为这指向 JSONObject d = dataitems.getJSONObject(i); 行。我相信它是定义的。我也试过没有运气 public String d; 但这会导致我刚才提到的代码出错。
我会很感激任何想法。
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class ParseJSON {
{
// Hashmap for ListView
ArrayList<HashMap<String, String>> dataList = new ArrayList<HashMap<String, String>>();
//Get the data (public static JSONObject getJSONfromURL(String url))
//JSONObject json = ParseJSON.getJSONfromURL("http://api.geonames.org/postalCodeSearchJSON?formatted=true&postalcode=9791&maxRows=10&username=demo&style=full");
JSONObject json = ParseJSON.getJSONfromURL(Globals.ParseJSONurl);
try{
//Get the element that holds the dataitem ( JSONArray )
JSONArray dataitems = json.getJSONArray("dataitem");
//Loop the Array
for(int i=0;i < dataitems.length();i++){
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
JSONObject d = dataitems.getJSONObject(i);
// D not working ?
// add items from doddataitemObj to dataitem string
String PUBLICEVENTTYPE = d.getString(PUBLICEVENTTYPE);
// adding each child node to HashMap key => value
map.put(PUBLICEVENTTYPE, PUBLICEVENTTYPE);
// adding HashList to ArrayList
dataList.add(map);
}
}catch(Exception e) {
e.printStackTrace();
Log.e("log_tag", "Error parsing data "+e.toString());
}
}
public static JSONObject getJSONfromURL(String url){
//initialize
InputStream is = null;
String result = "";
JSONObject jArray = null;
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//try parse the string to a JSON object
try{
jArray = new JSONObject(result);
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
return jArray;
}
}