NetworkOnMainThreadException

时间:2014-09-04 10:19:11

标签: android

尝试在我的应用中读取和解析一些json数据。我实现了扩展AsyncTask的Parser类,如下所示:

public class JSONParser extends AsyncTask<Void, Void, String> {
    private String strUrl;
    private List<NameValuePair> params;
    private String result;
    private String response;
    public static final String RESULT_SUCCESS = "success";
    public static final String RESULT_FAILED = "failed";

    public JSONParser(String strUrl, List<NameValuePair> params) {
        this.strUrl = strUrl;
        this.params = params;
    }

    private void parse() {
        try {
            // Create a new HttpClient and Post Header
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(strUrl);

            // Add parameters
            if (params != null) {
                httppost.setEntity(new UrlEncodedFormEntity(params));
            }

            // Execute HTTP Post Request
            HttpResponse httpResponse = httpclient.execute(httppost);

            // return by response
            result = RESULT_SUCCESS;
            this.response = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");

        } catch (Exception e) {
            result = RESULT_FAILED;
            this.response = null;
            e.printStackTrace();
        }
    }

    @Override
    public String doInBackground(Void... params) {
        parse();
        return response;
    }

    public String getResult() {
        return result;
    }

    public String getResponse() {
        return response;
    }
}

它在以后的Android版本中运行良好,但遗憾的是它会在旧版本中抛出NetworkOnMainThreadException。 我已经搜索过,发现我应该在我的应用程序中使用严格模式,但线程的性能变得非常糟糕!当我点击解析按钮时,它会冻结! 你能帮我找到更好的解决方案吗?

1 个答案:

答案 0 :(得分:3)

像这样打电话给你,它会解决你的问题!!

new JSONParser().execute();