TKV
TKV

Reputation: 2663

Error while calling webservice from android class

I had written a class in android which will consume a webservice to read some data from the webservice.

When am accessing that webservice through the URL call am getting that response xml properly. I had deployed the webservice in my local server and my url something like http://localhost:8083/TestWebService/services/GetDatabaseRecords?wsdl.

Following is the code portion am using to consume webservice in my app.

private String METHOD_NAME = "getSupplierDetails"; // our webservice method name
private String NAMESPACE = "http://test.webservice.com/"; // Here package name in webservice with reverse order.
private String SOAP_ACTION = NAMESPACE + METHOD_NAME; // NAMESPACE + method name
private static final String URL = "http://my-machine-ip:8083/TestWebService/services/GetDatabaseRecords?wsdl";

        SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);

        envelope.setOutputSoapObject(request);
        HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
        androidHttpTransport.debug = true;
        androidHttpTransport.call(SOAP_ACTION,envelope);
        SoapObject so = (SoapObject)envelope.bodyIn;

Following is the exception am getting when runnning the application.

android.os.NetworkOnMainThreadException:null

Is something wrong with my code? Experts please help.

Upvotes: 0

Views: 500

Answers (2)

breakline
breakline

Reputation: 6073

You have to use a background thread for these kind of tasks in Android. Frankly Android provides the AsyncTask type which is exactly for what you're trying to do. Something like:

private class WebserviceTask extends AsyncTask<String, Void, Object> {
 protected void doInBackground(String... parameters) {
     //do web service things here
     return result; //This is the parameter of onPostExecute, change type accordingly
 }

 protected void onPostExecute(Object result) {
     //do something with the result
 }
}

Usage:

WebserviceTask  task = new WebserviceTask();
task.execute("http://www.example.com/api"); //You can pass the parameters like this

Dont forget to add the

<uses-permission android:name="android.permission.INTERNET" /> 

line to your manifest as well.

Hope this helps

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500335

As the exception suggests, you're trying to use the network (i.e. a potentially slow, blocking resource) from the main (UI) thread. Android doesn't let you do that - you should perform network access on a separate thread to keep the UI responsive.

See the "Designing for Responsiveness" guidance for more details.

Upvotes: 2

Related Questions