-3

i have this java class:

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity
{
private static final String SOAP_ACTION = "http://tempuri.org/findContact";

private static final String OPERATION_NAME = "findContact";// your webservice web method name

private static final String WSDL_TARGET_NAMESPACE = "http://tempuri.org/";

private static final String SOAP_ADDRESS = "http://10.0.2.2:20959/test/Service.asmx";


TextView tvData1;
EditText edata;
Button button;
String studentNo;

@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    tvData1 = (TextView)findViewById(R.id.textView);

    button=(Button)findViewById(R.id.button);

    button.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {

            SoapObject request = new SoapObject(WSDL_TARGET_NAMESPACE,     OPERATION_NAME);
            PropertyInfo propertyInfo = new PropertyInfo();
            propertyInfo.type = PropertyInfo.STRING_CLASS;
            propertyInfo.name = "eid";

            edata =(EditText)findViewById(R.id.editText);
            studentNo=edata.getText().toString();

            request.addProperty(propertyInfo, studentNo);

            SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
                    SoapEnvelope.VER11);
            envelope.dotNet = true;

            envelope.setOutputSoapObject(request);

            HttpTransportSE httpTransport = new HttpTransportSE(SOAP_ADDRESS);

            try  {
                httpTransport.call(SOAP_ACTION, envelope);
                Object response = envelope.getResponse();
                tvData1.setText(response.toString());
            }  catch (Exception exception)   {
                tvData1.setText(exception.toString()+"  Or enter number is not Available!");
            }

            tvData1 = (TextView)findViewById(R.id.textView);

        }
    });


}

}

Which calls a webservice i created in C#. And im using Android Studio to create an application that call this webservice.

But when i run it i got this error:

android.os.NetworkOnMainThreadException

BTW I added the internet permission in the manifest.

How to solve this?

Lamawy
  • 603
  • 1
  • 7
  • 12

3 Answers3

0

you have to make asyncTask

public class MainActivity extends Activity{
...
....
 class CallWeb extends AsyncTask<String , String , String>{

    @Override
    protected String doInBackground(String... params) {

        HttpTransportSE httpTransport = new  HttpTransportSE(SOAP_ADDRESS);

        try  {
            httpTransport.call(SOAP_ACTION, envelope);
            Object response = envelope.getResponse();
            tvData1.setText(response.toString());
        }  catch (Exception exception)   {
            tvData1.setText(exception.toString()+"  Or enter number is not Available!");
        }

        return null;
    }
    }

I am just giving you basic idea you have to set your own and you need to understand this error. please go through this link also.

AsyncTask Example

AsyncTask

Network in mainthread

curiousMind
  • 2,812
  • 1
  • 17
  • 38
0

Applications which target Honeycomb SDK or higher will throw Networkonmainthreadexception. Earlier versions are allowed to do networking on this main thread but it is heavily discouraged (see ‘Keeping Your App Responsive’). Basically this is caused by requesting network access from the UI thread which would disrupt the user experience due to these often expensive operations.

Instead, these operations need to happen on a worker thread, and to do so you need to use some sort of thread or handler. The most common being an AsyncTask.

See http://developer.android.com/reference/android/os/AsyncTask.html for the android documented usage of this but it basically boils down to the following implementation:

A private subclass which extends AsyncTask which Implements the following methods:

  1. onPreExecute – Invoked on the UI thread before the task is executed and is used for setting stuff up (e.g showing the progress bar)

  2. doInBackground – The actual operation you want to perform which is fired immediately after onPreExecute

  3. onPostExecute – Invoked on the UI thread after doInBackground completes. This takes in the result from doInBackground as a parameter and can then be used on the UI thread.

An AsyncTask is used for operations which aren’t permitted on the UI thread such as:

  • Opening a socket connection
  • HTTP requests (such as HTTPClient and HTTPURLConnection)
  • Attempting to connect to a remote MySQL database
  • Downloading a file

Your current code is sitting in a method which will be created on the UI thread (which will throw a NetworkOnMainThreadException), so you need to move your code over to a thread not running on the main/UI thread to stop it from blocking the UI whilst your operations go on.

Smittey
  • 2,475
  • 10
  • 28
  • 35
0

The MainThreadException comes when you try to make network calls in the main task. Usually the screen and app freeze while they execute so Android has forbidden it. So in this case you have to create an AsyncTask.

Create an AsyncTask like this:

private class MyTask extends AsyncTask<String, Void, String>{

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressDialog = new ProgressDialog(YourActivity.this);
            progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            progressDialog.setIndeterminate(true);
            progressDialog.setMessage("Please Wait");
            progressDialog.setCancelable(false);
            progressDialog.show();
        }

        @Override
        protected String doInBackground(String... params) {
            try {
                url = new URL(params[0]);
                urlConnection =(HttpURLConnection) url.openConnection();
                urlConnection.connect();
                urlConnection.setConnectTimeout(5000);
                InputStream in = new BufferedInputStream(urlConnection.getInputStream());
                SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
                SoapEnvelope.VER11);
                envelope.dotNet = true;
                envelope.setOutputSoapObject(request);
                HttpTransportSE httpTransport = new HttpTransportSE(SOAP_ADDRESS);
            try  {
                httpTransport.call(SOAP_ACTION, envelope);
                Object response = envelope.getResponse();

            }catch (Exception exception)   {
                tvData1.setText(exception.toString()+"  Or enter number is not Available!");
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return response;
        }

        private StringBuilder inputStreamToString(InputStream is) {
            String rLine = "";
            StringBuilder answer = new StringBuilder();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is));
            try {
                while ((rLine = rd.readLine()) != null) {
                    answer.append(rLine);
                }
            } catch (Exception e) {
                MainActivity.this.finish();
            }
            return answer;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            progressDialog.dismiss();
            tvData1.setText(result.toString());
        }
    }

and then in your onCreate() you should can something like this

new MyTask().execute();
Kostas Drak
  • 3,222
  • 6
  • 28
  • 60