即使在AsyncTask中运行,android.os.NetworkOnMainThreadException也会出错

1 java android thread-synchronization

当我尝试连接到互联网时,我得到android.os.NetworkOnMainThreadException错误.我知道android(HoneyComb以后)的更新版本不允许你在UI线程上执行网络IO这就是我使用AsyncTask的原因.no错误代码但运行时,我得到android.os.NetworkOnMainThreadException错误代码:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.mainactivity);
    new GetProductDetails().execute();
}

class GetProductDetails extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(MainActivity.this);
        pDialog.setMessage("Loading product details. Please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    /**
     * Getting product details in background thread
     * */
    protected String doInBackground(String... params) {

        // updating UI from Background Thread
        runOnUiThread(new Runnable() {
            public void run() {
                // Check for success tag
                int success;
                try {
                    // Building Parameters
                    List<NameValuePair> params = new ArrayList<NameValuePair>();
                    params.add(new BasicNameValuePair("pid", pid));

                    // getting product details by making HTTP request
                    // Note that product details url will use GET request
                    JSONObject json = jsonParser.makeHttpRequest(
                            url_product_details, "GET", params);

                    // check your log for json response
                    Log.d("Single Product Details", json.toString());

                    // json success tag
                    success = json.getInt(TAG_SUCCESS);
                    if (success == 1) {
                        // successfully received product details
                        JSONArray productObj = json
                                .getJSONArray(TAG_PRODUCT); // JSON Array

                        // get first product object from JSON Array
                        JSONObject product = productObj.getJSONObject(0);


                        txtName = (EditText) findViewById(R.id.inputName);
                        txtPrice = (EditText) findViewById(R.id.inputPrice);
                        txtDesc = (EditText) findViewById(R.id.inputDesc);

                        // display product data in EditText
                        txtName.setText(product.getString(TAG_NAME));
                        txtPrice.setText(product.getString(TAG_PRICE));
                        txtDesc.setText(product.getString(TAG_DESCRIPTION));


                    }else{
                        // product with pid not found
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

        return null;
    }


    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url) {
        // dismiss the dialog once got all details
        pDialog.dismiss();
    }
}
Run Code Online (Sandbox Code Playgroud)

我已经读过一个可能的解决方案是使用StrictMode策略,但我有点不愿意使用它,因为它仅在开发环境中推荐.这里有什么问题?

Com*_*are 6

这有什么问题?

你是主应用程序线程上做网络I/O,从里面的Runnable你使用runOnUiThread().

摆脱runOnUiThread()Runnable.将网络代码放入doInBackground().更新您的小部件onPostExecute().从数据传递doInBackground()onPostExecute()通过从返回值要么doInBackground()(成为传递给参数onPostExecute())的内部或数据成员AsyncTask本身.