0

在下面的代码中,我在运行我的 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

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

4

4 回答 4

4

这是因为你正在做网络操作 Main UI thread

如果您使用线程来执行网络操作,那么您可以使用此代码段

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

在你的OnCreate()

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

您可以通过访问此链接了解更多信息

或者可以使用下面的代码

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});
于 2014-03-04T10:41:53.037 回答
1

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

于 2014-03-04T10:40:51.127 回答
0
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;
        }}
于 2014-03-04T10:50:41.360 回答
0

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

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

于 2014-03-04T10:41:33.657 回答