【问题标题】:setText from a parsed JSON object with AsyncTask [duplicate]来自使用 AsyncTask 解析的 JSON 对象的 setText [重复]
【发布时间】:2013-02-11 08:06:57
【问题描述】:

我正在制作一个从互联网网页源代码解析 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();
                }
            }
        }
    }
}

【问题讨论】:

  • 你收到的是NetworkOnMainThreadException 对吧?
  • 在你要求之前先谷歌一下。

标签: android json android-asynctask httpclient


【解决方案1】:

您可以这样做(此代码仅用于说明,根据需要更改)

class MyAsyncTask extends AsyncTask<String, Void, JSONObject> {
     protected void onPreExecute() {
        // You can set your activity to show busy indicator
        //setProgressBarIndeterminateVisibility(true);
     }

    protected JSONObject doInBackground(String... args) {
        return jsonStuffs();
    }

    protected void onPostExecute(final JSONObject jsonObj) {
        String temperature = jsonObj.getString("temperature");
        TextView tvTemp = (TextView)findViewById(R.id.textView);
        tvTemp.setText(temperature);
        // Stop busy indicator
        //setProgressBarIndeterminateVisibility(false);
    }

调用这个任务使用new MyAsyncTask().execute();(如果需要你可以传递String参数来执行) 您可以将jsonStuffs() 更改为返回JSONObject

例如

private JSONObject jsonStuffs() {

     // ...

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

     // ...
 }

【讨论】:

    【解决方案2】:

    它在 android 2.2 中工作,但我现在需要它在 android 3.0 上, 这需要在 AsyncTask 上。

    => 是的,如果您在没有在线程内部实现(例如 AsyncTask)的情况下进行网络调用,它会在 3.0 中提供NetworkOnMainThreadException

    我有 AsyncTask 的背景知识,但我很困惑该放在哪里 这个那个。

    => 只需在 AsyncTask 的 doInBackground() 方法中包含 Web 调用逻辑,在您的情况下,在 doInBackground() 中调用 getInternetData()。

    仅供参考,在 doInBackground() 中执行长时间运行的任务时,您无法直接更新 UI。是的,如果您想更新 UI,请遵循以下任一操作:

    1. 从 onPostExecute() 方法更新 UI。
    2. 或在doInBackround() 中实现runOnUiThread()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-24
      • 2016-06-16
      • 1970-01-01
      • 2017-10-12
      相关资源
      最近更新 更多