繁体   English   中英

android.os.NetworkOnMainThreadException但我使用了AsyncTask

[英]android.os.NetworkOnMainThreadException but i used AsyncTask

我的班级使用http连接有问题。 错误是连接,我读错误意味着我必须使用AsyncTask,但我使用它,我的应用程序仍然无法正常工作。 这里有代码:

@Override
public void onCreate(Bundle savedInstanceState) {
    ...
    new GetCoursesDetails().execute();
}
class GetCoursesDetails extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(InfoCorsi.this);
        pDialog.setMessage("Loading courses 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 = jParser.makeHttpRequest(
                            url_info_corsi, "GET", params);

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

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

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



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

类jSONParser工作,因为我用它来为另一个类建立连接,在这种情况下的错误是android.os.NetworkOnMainThreadException类型:

1-18 13:44:46.478 23304-23318/? E/art: Failed sending reply to debugger: Broken pipe
11-18 13:44:53.635 23304-E/AndroidRuntime: FATAL EXCEPTION: main
11-18 13:44:53.635 23304-E/AndroidRuntime: Process: com.piemonteorientale.cus.cuspo, PID: 23304
11-18 13:44:53.635 23304-E/AndroidRuntime: android.os.NetworkOnMainThreadException
11-18 13:44:53.635 23304-E/AndroidRuntime:     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1147)
11-18 13:44:53.635 23304-E/AndroidRuntime:     at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:110)
11-18 13:44:53.635 23304-E/AndroidRuntime:     at libcore.io.IoBridge.connectErrno(IoBridge.java:137)
11-18 13:44:53.635 23304-E/AndroidRuntime:     at libcore.io.IoBridge.connect(IoBridge.java:122)
11-18 13:44:53.635 23304-E/AndroidRuntime:     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:183)
11-18 13:44:53.635 23304-E/AndroidRuntime:     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:456)
11-18 13:44:53.635 23304-E/AndroidRuntime:     at java.net.Socket.connect(Socket.java:882)
11-18 13:44:53.635 23304-E/AndroidRuntime:     at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:124)
11-18 13:44:53.635 23304-E/AndroidRuntime:     at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:149)
11-18 13:44:53.635 23304-E/AndroidRuntime:     at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:169)
11-18 13:44:53.635 23304-E/AndroidRuntime:     at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:124)
11-18 13:44:53.635 23304-E/AndroidRuntime:     at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:365)
11-18 13:44:53.635 23304-E/AndroidRuntime:     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:560)
11-18 13:44:53.635 23304-E/AndroidRuntime:     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:492)
11-18 13:44:53.635 23304-E/AndroidRuntime:     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:470)
11-18 13:44:53.635 23304-E/AndroidRuntime:     at com.piemonteorientale.cus.cuspo.JSONParser.makeHttpRequest(JSONParser.java:62)
11-18 13:44:53.635 23304-E/AndroidRuntime:     at com.piemonteorientale.cus.cuspo.InfoCorsi$GetCoursesDetails$1.run(InfoCorsi.java:89)
11-18 13:44:53.635 23304-E/AndroidRuntime:     at android.os.Handler.handleCallback(Handler.java:739)
11-18 13:44:53.635 23304-E/AndroidRuntime:     at android.os.Handler.dispatchMessage(Handler.java:95)
11-18 13:44:53.635 23304-E/AndroidRuntime:     at android.os.Looper.loop(Looper.java:135)
11-18 13:44:53.635 23304-E/AndroidRuntime:     at android.app.ActivityThread.main(ActivityThread.java:5290)
11-18 13:44:53.635 23304-E/AndroidRuntime:     at java.lang.reflect.Method.invoke(Native Method)
11-18 13:44:53.635 23304-E/AndroidRuntime:     at java.lang.reflect.Method.invoke(Method.java:372)
11-18 13:44:53.635 23304-E/AndroidRuntime:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
11-18 13:44:53.635 23304-E/AndroidRuntime:     at  com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)

摆脱runOnUiThread()doInBackground()方法。

如果要显示进度,可以使用AsyncTask.onProgressUpdate (Progress...) 此方法将在UI线程上运行。 不要通过它进行任何网络呼叫。 使用AsyncTask.publishProgress (Progress...) AsyncTask.doInBackground (Params...)方法中的AsyncTask.publishProgress (Progress...)来调用进度更新。

请参阅AsyncTask API文档

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM