android.os.NetworkOnMainThreadException while posting data to url

This question already has an answer here:

  • How do I fix android.os.NetworkOnMainThreadException? 48 answers

  • Its because you're doing network operation on Main UI thread

    if you're using threads to do network operations then you can use this code snippet

    if (android.os.Build.VERSION.SDK_INT > 9) {
    StrictMode.ThreadPolicy policy = 
            new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);
    }
    

    in your OnCreate()

    But its wrong practice to use above said operation, instead you should use AsyncTask class provided by android to handle properly network operation without blocking UI thread .

    you can learn more by visiting this LINK

    or can use the below code

    private class UploadFiles extends AsyncTask<String, Void, Void> {
         protected String doInBackground(String... urls) {
             //THIS METHOD WILL BE CALLED AFTER ONPREEXECUTE
             //YOUR NETWORK OPERATION HERE
             return null;
         }
    
         protected void onPreExecute() {
             super.onPreExecute();
             //THIS METHOD WILL BE CALLED FIRST
             //DO OPERATION LIKE SHOWING PROGRESS DIALOG PRIOR TO BEGIN NETWORK OPERATION
         }
    
         protected void onPostExecute(String result) {
             super.onPostExecute();
             //TNIS METHOD WILL BE CALLED AT LAST AFTER DOINBACKGROUND
             //DO OPERATION LIKE UPDATING UI HERE
         }
     }
    

    and you can simple call this class by writing

     new UploadFiles ().execute(new String[]{//YOUR LINK});
    

    You should connect to network using Asynctask, threads, handler not main thread. If you try to connect (do long time operations) using main UIThread you will see this error.


    This exception is thrown when an application attempts to perform a networking operation on its main thread. Run your code in AsyncTask or IntentService w

    see this example for how to handle network operations in asyncTask

    链接地址: http://www.djcxy.com/p/5030.html

    上一篇: 是否有可能只使用Eclipse和共享建立一个Java项目一次?

    下一篇: android.os.NetworkOnMainThreadException将数据发布到url