我正在制作一个从互联网网页的源代码中解析 JSON 文本的 android 程序。它在 android 2.2 中工作,但我现在需要它在 android 3.0 上,它需要在 AsyncTask 上。我有关于 AsyncTask 的背景,但我很困惑把这个和那个放在哪里。提前谢谢大家:)
这是我在 MainActivity 类中的方法:
private void jsonStuffs() {
//JSON PARSER & HOME PAGE TEXTVIEWS
client = new DefaultHttpClient();
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 in the JSON in the webpage
String temperature = obj.getString("temperature");
TextView tvTemp = (TextView)findViewById(R.id.textView);
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();
}
}
}
}
}