我是编程新手,我正在制作一个 json 解析器,但是我的线程方法无法访问,我该如何去做。当我调试时,它进入了我的 getjson 方法,但随后跳过了 run 方法。我已经在 stack over flow 上进行了搜索,但是我对线程非常困惑,有什么好的方法可以做到这一点吗?
public class jsonParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public jsonParser() {
}
public JSONObject getJSONFromUrl(final String url) {
Thread t = new Thread() {
public void run() {
Looper.prepare(); //For Preparing Message Pool for the child Thread
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
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();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {jObj = new JSONObject(json);
} catch (JSONException e) {
// TODO Auto-generated catch block
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
Looper.loop();
return;
}
}; t.start();
return jObj;
}
}