java - 即使在 AsyncTask 中运行时也出现 android.os.NetworkOnMainThreadException 错误

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

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

最佳答案

What's the problem here?

您正在主应用程序线程上执行网络 I/O,从您使用 runOnUiThread()Runnable 内部。

去掉 runOnUiThread()Runnable。将网络代码放在 doInBackground() 中。在 onPostExecute() 中更新您的小部件。您通过 doInBackground() 的返回值将数据从 doInBackground() 传递到 onPostExecute()(它成为传递给 onPostExecute()) 或 AsyncTask 本身内部的数据成员。

关于java - 即使在 AsyncTask 中运行时也出现 android.os.NetworkOnMainThreadException 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17221097/

相关文章:

java - Spring 启动: Consider defining a bean named 'entityManagerFactory' in your configuration

java - 将pojo序列化成不同的json结构

java - ARCore – 如何为 Transformable 节点设置默认比例?

java - 沿着标记移动相机

c# - Monitor.Wait 初始锁定?

java - 如何将此mongodb聚合命令转换为java代码

android - 膨胀 WebView XML 时出错

java - 如何避免在每个 Activity 和服务上安装和关闭 'HttpResponseCache'?

java - volatile 变量没有给出预期的输出

java - Java中类锁和对象锁的区别