Asynctask线程错误

时间:2014-04-14 00:10:14

标签: android

apears的错误是android.os.NetworkOnMainThreadException,这与runUithread有关,但我不知道如何更改它。我已经做了asynctask我不明白。请帮帮我。

 /**
 * Background Async Task to Get complete product details
 * */
class GetProductDetails extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(EditProductActivity.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("id", id2));

                    // getting product details by making HTTP request
                    // Note that product details url will use GET request
                    JSONObject json = jParser.makeHttpRequest(
                            url_product_detials, "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);

                        // product with this pid found
                        // Edit Text
                        txtdata1 = (EditText) findViewById(R.id.inputdt_ini);
                        txtdata2 = (EditText) findViewById(R.id.inputdt_fim);
                        txtDesc = (EditText) findViewById(R.id.inputDesc);

                        // display product data in EditText
                        txtdata1.setText(product.getString(TAG_DATA1));
                        txtdata2.setText(product.getString(TAG_DATA2));
                        txtDesc.setText(product.getString(TAG_DESCRICAO));

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

2 个答案:

答案 0 :(得分:1)

您必须在后台线程中执行网络操作,而不是UI线程,因为您正在执行runOnUiThread。因此,网络操作必须与对UI视图进行更改分开。

而是执行以下操作(一种方法):

  1. 删除runOnUiThread
  2. 将您的AsyncTask更改为AsyncTask<String, String, JSONObject>
  3. product
  4. 中返回doInBackground JSONObject
  5. onPostExecute中,您可以使用product
  6. 修改您的观点

    所以基本上这可以让您的网络操作全部在后台线程中完成,一旦完成,它将返回productonPostExecute以供您显示。

    您的代码示例(没有测试,但是为您提供了一般性的想法,并且没有包含onPreExecute,因为它与问题无关):

    /**
     * Background Async Task to Get complete product details
     */
    class GetProductDetails extends AsyncTask<String, String, JSONObject> {
    
        /**
         * Getting product details in background thread
         */
        protected JSONObject doInBackground(String... params) {
            // Check for success tag
            int success;
            try {
                // Building Parameters
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("id", id2));
    
                // getting product details by making HTTP request
                // Note that product details url will use GET request
                JSONObject json = jParser.makeHttpRequest(
                        url_product_detials, "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);
    
                    // instead return your product to onPostExecute
                    return product;
                } else {
                    // product with pid not found
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
    
            return null;
        }
    
        /**
         * After completing background task Dismiss the progress dialog
         * *
         */
        protected void onPostExecute(JSONObject product) {
            if (product != null) {
                // product with this pid found
                // Edit Text
                txtdata1 = (EditText) findViewById(R.id.inputdt_ini);
                txtdata2 = (EditText) findViewById(R.id.inputdt_fim);
                txtDesc = (EditText) findViewById(R.id.inputDesc);
    
                // display product data in EditText
                txtdata1.setText(product.getString(TAG_DATA1));
                txtdata2.setText(product.getString(TAG_DATA2));
                txtDesc.setText(product.getString(TAG_DESCRICAO));
            }
    
            // dismiss the dialog once got all details
            pDialog.dismiss();
        }
    }
    

答案 1 :(得分:0)

你是如此接近......在你致电JSONObject之前,做所有的事情来获取你的数据(也就是创建onUiThread()等...)你应该做的唯一的事情在onUiThread()进行操作应该在文本视图上调用setText()