【问题标题】:android.os.NetworkOnMainThreadException while posting data to url [duplicate]android.os.NetworkOnMainThreadException 将数据发布到 url [重复]
【发布时间】:2014-04-05 20:22:07
【问题描述】:

在下面的代码中,我在运行我的 Android 项目时遇到了错误

代码:

  try {                 
        Gson gson = new Gson();
        String json = gson.toJson(stockDetailData);
        String json1 = gson.toJson(stockMainData); 
        String json2 = gson.toJson(pledgerData);
        JSONObject jo = new JSONObject();                   

        jo.put("stockDetailData", json.toString());
        jo.put("stockMainData", json1.toString());
        jo.put("pledgerData", json2.toString());
        jo.put("company_id", "4");



        URL url = new URL("http://127.0.0.1:180/AfaqTraders/index.php/sale/saveVoucher");

        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url.toURI());

        // Prepare JSON to send by setting the entity
        httpPost.setEntity(new StringEntity(jo.toString(), "UTF-8"));

        // Set up the header types needed to properly transfer JSON
        httpPost.setHeader("Content-Type", "application/json");
        httpPost.setHeader("Accept-Encoding", "application/json");
        httpPost.setHeader("Accept-Language", "en-US");

        // Execute POST
        HttpResponse response = httpClient.execute(httpPost);                   
    } catch(Exception e) {
        Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
    }

错误: android.os.NetworkOnMainThreadException

我一直在寻找错误,但找不到。谁能告诉我我在这里做错了什么??

【问题讨论】:

标签: android networkonmainthread thread-exceptions


【解决方案1】:

您应该使用 Asynctask、线程、处理程序而不是主线程连接到网络。如果您尝试使用主 UIThread 连接(执行长时间操作),您将看到此错误。

【讨论】:

    【解决方案2】:

    当应用程序尝试在其主线程上执行网络操作时会引发此异常。在 AsyncTask 或 IntentService w 中运行您的代码

    请参阅this 示例了解如何在 asyncTask 中处理网络操作

    【讨论】:

      【解决方案3】:

      因为你在Main UI thread进行网络操作

      如果您使用线程来执行网络操作 那么你可以使用这个代码sn-p

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

      在你的OnCreate()

      但是使用上述操作是错误的做法,你应该使用android提供的AsyncTask类来正确处理网络操作without blocking UI thread

      您可以访问LINK了解更多信息

      或者可以使用下面的代码

      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
           }
       }
      

      你可以通过编写来简单地调用这个类

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

      【讨论】:

        【解决方案4】:
        you should use asynctask [asynctask][1]
        
        
          [1]: http://developer.android.com/reference/android/os/AsyncTask.html
        
        > class async extends AsyncTask<Params, Progress, Result>
            //Params used in the asynctask
            //Progress for progress bar
            //Result here the result of parsing
            {@Override
        
            protected void onPreExecute() {
        //before parsing you can launch a progress bar
        
                super.onPreExecute();
            }
        
            @Override
                protected void onPostExecute(Void result) {
        
                //processing after parsing
        
        
        
                super.onPostExecute(result);
                }
        
                @Override
                protected Void doInBackground(Void... params) {
        // parsing here
                    return null;
                }}
        

        【讨论】:

        • 你现在可以看到我的回复了,我更新了它;)
        猜你喜欢
        • 1970-01-01
        • 2014-10-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-01-19
        • 2019-01-25
        • 1970-01-01
        相关资源
        最近更新 更多