我正在制作一个从互联网获取 JSON 数据的 Android 程序。JSON 文本来自网页的源代码(使用 HttpClient),然后对其进行解析并显示到 TextView。这适用于 Froyo,但我需要它在 AsyncTask 上才能在 Honeycomb 及更高版本上工作。
由于这个 AsyncTask 问题,我现在很困惑。我尝试并遵循了一些教程,但它与我想做的不同。我只是得到错误,我很沮丧。谢谢您的帮助!:)
这是我在 MainActivity 类上的方法:
private void jsonStuffs() {
// TODO Auto-generated method stub
//JSON PARSER & HOME PAGE TEXTVIEWS
client = new DefaultHttpClient();
//new Read().execute("id");
//http client codes only no parser !!
GetMethodEx test = new GetMethodEx();
String returned;
try {
returned = test.getInternetData();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try{
String jsonStr = test.getInternetData(); //go to GetMethodEx
JSONObject obj = new JSONObject(jsonStr);
//find temperature on JSON on webpage
String temperature = obj.getString("temperature");
TextView tvTemp = (TextView)findViewById(R.id.temp);
tvTemp.setText(temperature);
}
//catch (JSONException e) {
// e.printStackTrace();
//}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
这是我的 GetMethodEx 类:
public class GetMethodEx extends Activity {
public String getInternetData() throws Exception{
BufferedReader in = null;
String data = null;
//
try{
HttpClient client = new DefaultHttpClient();
URI website = new URI("http://nhjkv.comuf.com/json_only.php");
HttpGet request = new HttpGet();
request.setURI(website);
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String l = "";
String nl = System.getProperty("line.separator");
while ((l = in.readLine()) !=null){
sb.append(l + nl);
}
in.close();
data = sb.toString();
return data;
}finally {
if (in !=null){
try{
in.close();
return data;
} catch (Exception e){
e.printStackTrace();
}
}
}
}
}