NetworkOnMainThreadException错误logCat

时间:2014-01-10 17:33:52

标签: android http android-asynctask

我正在开发一个详细信息表单,当我将Intent中的值传递给此表单时,它不起作用并打印此错误:android.os.NetworkOnMainThreadException。这是我的代码:

public class VoyageDetails extends Activity{

private ProgressDialog pDialog;

String idp;

TextView villeDe;
TextView villeA;
TextView DateD;
TextView HeureD;
TextView Nom;
TextView Prenom;
TextView prix;
TextView voiture;
TextView tel;
TextView autre;

JSONObject Empleado;

JSONParser jsonParser = new JSONParser();

private static final String url_detalles_empleado = "http://sorifgroupcom.ipage.com/Android/Voyage_Details.php";

private static final String TAG_SUCCESS = "success";
private static final String TAG_VoyageDetails = "VoyageDetails";
private static final String TAG_IDP = "idp";
private static final String TAG_VILLEDE = "ville_depart";
private static final String TAG_VILLEA = "ville_arrivee";
private static final String TAG_DATED = "date_depart";
private static final String TAG_HEURED = "heure_depart";
private static final String TAG_NOM = "nom";
private static final String TAG_PRENOM = "prenom";
private static final String TAG_VOITURE = "voiture";
private static final String TAG_TEL = "tel";
private static final String TAG_PRIX = "prix";
private static final String TAG_AUTRE = "autre";

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.voyage_details);
    Intent i = getIntent();

    // getting Empleado id (pid) from intent
    idp = i.getStringExtra(TAG_IDP);
    Log.i("tesssst", idp);
    villeDe = (TextView) findViewById(R.id.VilleDe);
    villeA = (TextView) findViewById(R.id.villeA);
    DateD = (TextView) findViewById(R.id.DateD);
    HeureD = (TextView) findViewById(R.id.HeureD);
    Nom = (TextView) findViewById(R.id.Nom);
    Prenom = (TextView) findViewById(R.id.Prenom);
    prix = (TextView) findViewById(R.id.PrixDe);
    tel = (TextView) findViewById(R.id.telD);
    voiture = (TextView) findViewById(R.id.Voiture);
    autre = (TextView) findViewById(R.id.AutreD);
    new GetEmpleadoDetails().execute();
}

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

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

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

        // updating UI from Background Thread

                // Check for success tag
                int success;
                try {
                    // Building Parameters
                    List<NameValuePair> params = new ArrayList<NameValuePair>();
                    params.add(new BasicNameValuePair("idp", idp));

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

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

                    // json success tag
                    success = json.getInt(TAG_SUCCESS);
                    if (success == 1) {
                        // successfully received Empleado details
                        JSONArray VoyageDetailsObj = json
                                .getJSONArray(TAG_VoyageDetails); // JSON Array

                        // get first Empleado object from JSON Array
                        Empleado = VoyageDetailsObj.getJSONObject(0);

                        // Empleado with this pid found
                        // Edit Text

                        // display Empleado data in EditText


                    }else{
                        // Empleado 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();
        try {
        villeDe.setText(Empleado.getString(TAG_VILLEDE));
        villeA.setText(Empleado.getString(TAG_VILLEA));
        DateD.setText(Empleado.getString(TAG_DATED));
        HeureD.setText(Empleado.getString(TAG_HEURED));
        Nom.setText(Empleado.getString(TAG_NOM));
        Prenom.setText(Empleado.getString(TAG_PRENOM));
        prix.setText(Empleado.getString(TAG_PRIX));
        tel.setText(Empleado.getString(TAG_TEL));
        voiture.setText(Empleado.getString(TAG_VOITURE));
        autre.setText(Empleado.getString(TAG_AUTRE));
        } catch (Exception e) {
            // TODO: handle exception
        }

    }
}
}

logCat print:

1-10 18:00:17.992: E/AndroidRuntime(850): FATAL EXCEPTION: AsyncTask #3
01-10 18:00:17.992: E/AndroidRuntime(850): java.lang.RuntimeException: An error occured while executing doInBackground()
01-10 18:00:17.992: E/AndroidRuntime(850):  at android.os.AsyncTask$3.done(AsyncTask.java:299)
01-10 18:00:17.992: E/AndroidRuntime(850):  at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
01-10 18:00:17.992: E/AndroidRuntime(850):  at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
01-10 18:00:17.992: E/AndroidRuntime(850):  at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
01-10 18:00:17.992: E/AndroidRuntime(850):  at java.util.concurrent.FutureTask.run(FutureTask.java:137)
01-10 18:00:17.992: E/AndroidRuntime(850):  at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
01-10 18:00:17.992: E/AndroidRuntime(850):  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
01-10 18:00:17.992: E/AndroidRuntime(850):  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
01-10 18:00:17.992: E/AndroidRuntime(850):  at java.lang.Thread.run(Thread.java:856)
01-10 18:00:17.992: E/AndroidRuntime(850): Caused by: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
01-10 18:00:17.992: E/AndroidRuntime(850):  at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:4609)
01-10 18:00:17.992: E/AndroidRuntime(850):  at android.view.ViewRootImpl.requestLayout(ViewRootImpl.java:835)
01-10 18:00:17.992: E/AndroidRuntime(850):  at android.view.View.requestLayout(View.java:15129)
01-10 18:00:17.992: E/AndroidRuntime(850):  at android.view.View.requestLayout(View.java:15129)
01-10 18:00:17.992: E/AndroidRuntime(850):  at android.view.View.requestLayout(View.java:15129)
01-10 18:00:17.992: E/AndroidRuntime(850):  at android.view.View.requestLayout(View.java:15129)
01-10 18:00:17.992: E/AndroidRuntime(850):  at android.view.View.requestLayout(View.java:15129)
01-10 18:00:17.992: E/AndroidRuntime(850):  at android.widget.TableLayout.requestLayout(TableLayout.java:226)
01-10 18:00:17.992: E/AndroidRuntime(850):  at android.view.View.requestLayout(View.java:15129)
01-10 18:00:17.992: E/AndroidRuntime(850):  at android.view.View.requestLayout(View.java:15129)
01-10 18:00:17.992: E/AndroidRuntime(850):  at android.widget.TextView.checkForRelayout(TextView.java:6309)
01-10 18:00:17.992: E/AndroidRuntime(850):  at android.widget.TextView.setText(TextView.java:3547)
01-10 18:00:17.992: E/AndroidRuntime(850):  at android.widget.TextView.setText(TextView.java:3405)
01-10 18:00:17.992: E/AndroidRuntime(850):  at android.widget.TextView.setText(TextView.java:3380)
01-10 18:00:17.992: E/AndroidRuntime(850):  at org.Soufiane.voyagesociale.VoyageDetails$GetEmpleadoDetails.doInBackground(VoyageDetails.java:134)
01-10 18:00:17.992: E/AndroidRuntime(850):  at org.Soufiane.voyagesociale.VoyageDetails$GetEmpleadoDetails.doInBackground(VoyageDetails.java:1)
01-10 18:00:17.992: E/AndroidRuntime(850):  at android.os.AsyncTask$2.call(AsyncTask.java:287)
01-10 18:00:17.992: E/AndroidRuntime(850):  at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
01-10 18:00:17.992: E/AndroidRuntime(850):  ... 5 more
01-10 18:00:21.491: E/BufferQueue(35): [org.Soufiane.voyagesociale/org.Soufiane.voyagesociale.VoyageDetails] drainQueueLocked: BufferQueue has been abandoned!
01-10 18:00:22.040: E/WindowManager(850): Activity org.Soufiane.voyagesociale.VoyageDetails has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@4149bdd0 that was originally added here
01-10 18:00:22.040: E/WindowManager(850): android.view.WindowLeaked: Activity org.Soufiane.voyagesociale.VoyageDetails has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@4149bdd0 that was originally added here
01-10 18:00:22.040: E/WindowManager(850):   at android.view.ViewRootImpl.<init>(ViewRootImpl.java:374)
01-10 18:00:22.040: E/WindowManager(850):   at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:292)
01-10 18:00:22.040: E/WindowManager(850):   at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:224)
01-10 18:00:22.040: E/WindowManager(850):   at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:149)
01-10 18:00:22.040: E/WindowManager(850):   at android.view.Window$LocalWindowManager.addView(Window.java:547)
01-10 18:00:22.040: E/WindowManager(850):   at android.app.Dialog.show(Dialog.java:277)
01-10 18:00:22.040: E/WindowManager(850):   at org.Soufiane.voyagesociale.VoyageDetails$GetEmpleadoDetails.onPreExecute(VoyageDetails.java:85)
01-10 18:00:22.040: E/WindowManager(850):   at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
01-10 18:00:22.040: E/WindowManager(850):   at android.os.AsyncTask.execute(AsyncTask.java:534)
01-10 18:00:22.040: E/WindowManager(850):   at org.Soufiane.voyagesociale.VoyageDetails.onCreate(VoyageDetails.java:69)
01-10 18:00:22.040: E/WindowManager(850):   at android.app.Activity.performCreate(Activity.java:5008)
01-10 18:00:22.040: E/WindowManager(850):   at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
01-10 18:00:22.040: E/WindowManager(850):   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
01-10 18:00:22.040: E/WindowManager(850):   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
01-10 18:00:22.040: E/WindowManager(850):   at android.app.ActivityThread.access$600(ActivityThread.java:130)
01-10 18:00:22.040: E/WindowManager(850):   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
01-10 18:00:22.040: E/WindowManager(850):   at android.os.Handler.dispatchMessage(Handler.java:99)
01-10 18:00:22.040: E/WindowManager(850):   at android.os.Looper.loop(Looper.java:137)
01-10 18:00:22.040: E/WindowManager(850):   at android.app.ActivityThread.main(ActivityThread.java:4745)
01-10 18:00:22.040: E/WindowManager(850):   at java.lang.reflect.Method.invokeNative(Native Method)
01-10 18:00:22.040: E/WindowManager(850):   at java.lang.reflect.Method.invoke(Method.java:511)
01-10 18:00:22.040: E/WindowManager(850):   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786) 
01-10 18:00:22.040: E/WindowManager(850):   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
01-10 18:00:22.040: E/WindowManager(850):   at dalvik.system.NativeStart.main(Native Method)

JsonParser:

public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

// constructor
public JSONParser() {

}

// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
        List<NameValuePair> params) {

    // Making HTTP request
    try {

        // check for request method
        if(method == "POST"){
            // request method is POST
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        }else if(method == "GET"){
            // request method is GET
            DefaultHttpClient httpClient = new DefaultHttpClient();
            String paramString = URLEncodedUtils.format(params, "utf-8");
            url += "?" + paramString;
            HttpGet httpGet = new HttpGet(url);

            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        }           


    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;

}

3 个答案:

答案 0 :(得分:2)

您需要删除

   runOnUiThread(new Runnable() {
        public void run() {
doInbackground

中的

同时将所有初始化移至onCreate

  villeDe = (TextView) findViewById(R.id.VilleDe);
  villeA = (TextView) findViewById(R.id.villeA);
  DateD = (TextView) findViewById(R.id.DateD);
  HeureD = (TextView) findViewById(R.id.HeureD);
  Nom = (TextView) findViewById(R.id.Nom);
  Prenom = (TextView) findViewById(R.id.Prenom);
  pvoiture = (TextView) findViewById(R.id.Voiture);
  autre = (TextView) findViewById(R.id.AutreD);

所有这些都归onPostExecute

  villeDe.setText(Empleado.getString(TAG_VILLEDE));
  villeA.setText(Empleado.getString(TAG_VILLEA));
  DateD.setText(Empleado.getString(TAG_DATED));
  HeureD.setText(Empleado.getString(TAG_HEURED));
  Nom.setText(Empleado.getString(TAG_NOM));
  Prenom.setText(Empleado.getString(TAG_PRENOM));
  prix.setText(Empleado.getString(TAG_PRIX));
  tel.setText(Empleado.getString(TAG_TEL));
  voiture.setText(Empleado.getString(TAG_VOITURE));
  autre.setText(Empleado.getString(TAG_AUTRE));

答案 1 :(得分:1)

关键词:

  1. 从不runOnUiThread线程执行用户界面,即使在doInBackground中也是如此!这打败了AsyncTask的全部意义!!!!
  2. OnProgressUpdate或OnPostExecute
  3. 中填写您的UI内容
  4. 根据需要设置格式。
  5. 鉴于此,这是一个如何正确执行此操作的示例。请注意,可能存在一些轻微的语法错误。

    class GetEmpleadoDetails extends AsyncTask<String, String, JSonObject> {
    
        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(VoyageDetails.this);
            pDialog.setMessage("Loading Empleado details. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }
    
        /**
         * Getting Empleado details in background thread
         * */
        protected JSONObject doInBackground(String... params) {
                    JSONObject json=null;
                    try {
                        // Building Parameters
                        List<NameValuePair> params = new ArrayList<NameValuePair>();
                        params.add(new BasicNameValuePair("idp", idp));
    
                        // getting Empleado details by making HTTP request
                        // Note that Empleado details url will use GET request
                        json = jsonParser.makeHttpRequest(
                                url_detalles_empleado, "GET", params);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    return json;
        }
    
    @Override
    protected void onPostExecute(JSonObject json) {
    
                    // json success tag
                    int success = json.getInt(TAG_SUCCESS);
                    if (success == 1) {
                        // successfully received Empleado details
                        JSONArray VoyageDetailsObj = json
                                .getJSONArray(TAG_VoyageDetails); // JSON Array
    
                        // get first Empleado object from JSON Array
                        JSONObject Empleado = VoyageDetailsObj.getJSONObject(0);
    
                        // Empleado with this pid found
                        // Edit Text
                        villeDe = (TextView) findViewById(R.id.VilleDe);
                        villeA = (TextView) findViewById(R.id.villeA);
                        DateD = (TextView) findViewById(R.id.DateD);
                        HeureD = (TextView) findViewById(R.id.HeureD);
                        Nom = (TextView) findViewById(R.id.Nom);
                        Prenom = (TextView) findViewById(R.id.Prenom);
                        prix = (TextView) findViewById(R.id.PrixDe);
                        tel = (TextView) findViewById(R.id.telD);
                        voiture = (TextView) findViewById(R.id.Voiture);
                        autre = (TextView) findViewById(R.id.AutreD);
                        // display Empleado data in EditText
                        villeDe.setText(Empleado.getString(TAG_VILLEDE));
                        villeA.setText(Empleado.getString(TAG_VILLEA));
                        DateD.setText(Empleado.getString(TAG_DATED));
                        HeureD.setText(Empleado.getString(TAG_HEURED));
                        Nom.setText(Empleado.getString(TAG_NOM));
                        Prenom.setText(Empleado.getString(TAG_PRENOM));
                        prix.setText(Empleado.getString(TAG_PRIX));
                        tel.setText(Empleado.getString(TAG_TEL));
                        voiture.setText(Empleado.getString(TAG_VOITURE));
                        autre.setText(Empleado.getString(TAG_AUTRE));
    
                    }else{
                        // Empleado with pid not found
                    }
        }
    

答案 2 :(得分:0)

您无法在UI线程中发出任何http请求。在runOnUiThread方法之前调用此代码:JSONObject json = jsonParser.makeHttpRequest(url_detalles_empleado, "GET", params);