0

我正在制作一个从互联网获取 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();
            }
        }
    }
}
}
4

3 回答 3

1

您不能在 doInBackground 方法中使用 findViewByID 和 textView。您可以在 onPostExecute 中使用 textView。

修改方法“jsonStuffs()”以便返回字符串。而且您不必将 getInternetData() 放到另一个活动类中。

它从您的 MainActivity.class 修改的方法

private String jsonStuffs() {
            // TODO Auto-generated method stub
        //JSON PARSER & HOME PAGE TEXTVIEWS

            client = new DefaultHttpClient();
            //new Read().execute("id");
            //http client codes only no parser !!

            String returned;
            try {
                returned = 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");
                    return temperature

            }
            //catch (JSONException e) {
                 // e.printStackTrace();
                //} 
            catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    return null;
                }
        }

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();
            }
        }
    }
}
}

然后像这样创建异步任务:

public class JsonDownloaderTask extends AsyncTask<Void, Void, String>{


    @Override
    protected Void doInBackground(Void... params) {
        return jsonStuff()
    }

    @Override
    protected void onPostExecute(String result){
        if(result != null){
            //DO YOUR STUFF WITH TEXTVIEW
        }
    }

}

您需要在 MainActivity.class 的 onCreate() 或 onResume() 方法中初始化 textView

于 2013-01-22T07:55:51.923 回答
1

将您的连接部分作为一个单独的类并将以下代码放入其中

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();
        }
    }
}
}

使用这个类作为你的服务

public class TaskAsync extends AsyncTask<String, String, String> {

private String response = null;

@Override
protected String doInBackground(String... params) {
    response = new ClassName().getInternetData();
    return response;
}

}

然后把它放在你的活动中

String response = new TaskAsync().execute("URL_WITH_PARAMETERS").get();
于 2013-01-22T07:34:13.603 回答
1

更改您的代码以使用 AsyncTask 进行网络服务调用:

private void jsonStuffs() {
            // TODO Auto-generated method stub

            try{

               new InternetDataOperation().execute("");

            }
            //catch (JSONException e) {
                 // e.printStackTrace();
                //} 
            catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
        }

private class InternetDataOperation extends AsyncTask<String, Void, String> {

      @Override
      protected void onPreExecute() {
      }

      @Override
      protected String doInBackground(String... params) {
        client = new DefaultHttpClient();

        GetMethodEx test = new GetMethodEx();
        String jsonStr = test.getInternetData(); //go to GetMethodEx
            return jsonStr;
      }      

      @Override
      protected void onPostExecute(String result) {  
         JSONObject obj = new JSONObject(result);

         //find temperature on JSON on webpage
         String temperature = obj.getString("temperature");
         TextView tvTemp = (TextView)findViewById(R.id.temp);
         tvTemp.setText(temperature);             
      }


}
于 2013-01-22T07:36:22.120 回答