In the below code I'm getting an error when running my Android project

Code:

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

Error: android.os.NetworkOnMainThreadException

I have been looking for the error but I'm unable to find it. Can anybody tell me what I'm doing wrong here??

有帮助吗?

解决方案

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

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;
        }}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top