androidsoapandroid-asynctask

android.os.NetworkOnMainThreadException even using an Aysnc task


I am trying to call a SOAP service with Android studio, but I am getting the following exception android.os.NetworkOnMainThreadException

I know should be when running a network call on the main thread, but I am using an async task so I was expecting not to have this exception

@RequiresApi(api = Build.VERSION_CODES.CUPCAKE)
    public void TEST()
    {
        new TESTROOT().doInBackground();
    }

    @SuppressLint("StaticFieldLeak")
    @RequiresApi(api = Build.VERSION_CODES.CUPCAKE)
    public class TESTROOT extends AsyncTask<Void, Void, Boolean> {
        protected Boolean doInBackground(Void... voids) {
            HttpURLConnection connection = null;
            try
            {
                URL url = new URL("http://webservices.oorsprong.org/websamples.countryinfo/CountryInfoService.wso");
                connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("POST");
                connection.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
                connection.setRequestProperty("SOAPAction", "http://webservices.oorsprong.org/websamples.countryinfo/CountryInfoService.wso/ListOfContinentsByName");
                connection.setDoOutput(true);
            }
            catch (Exception e) {
            }
            OutputStream os = null;
            try {
                os = connection.getOutputStream();
            } catch (Exception ex) {
                runOnUiThread(new Runnable() {
                        @SuppressLint("ShowToast")
                        public void run() {
                            Toast.makeText(getApplicationContext(), "" + ex, Toast.LENGTH_LONG).show();
                        }
                    });
            }

Can someone helps me to undestand what I am doing in the wrongly? thank you Andrea


Solution

  • new TESTROOT().doInBackground();

    You should not call doInBackground() yourself as then you are not using the asynctask.

    Start your task in the normal way like for example

    new TESTROOT().execute();