ashi sharma ashi sharma -4 years ago 65
Android Question

Connect .net Webservice with Android

Webservice class code :

public class WebService {

String namespace = "http://www.webserviceX.NET/";
private String url = "http://www.webservicex.net/ConvertWeight.asmx";

String SOAP_ACTION;
SoapObject request = null, objMessages = null;
SoapSerializationEnvelope envelope;
AndroidHttpTransport androidHttpTransport;

WebService() {
}
protected void SetEnvelope() {

try {

// Creating SOAP envelope
envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);

//You can comment that line if your web service is not .NET one.
envelope.dotNet = true;

envelope.setOutputSoapObject(request);
androidHttpTransport = new AndroidHttpTransport(url);
androidHttpTransport.debug = true;

} catch (Exception e) {
System.out.println("Soap Exception---->>>" + e.toString());
}
}

// MethodName variable is define for which webservice function will call
public String getConvertedWeight(String MethodName, String weight,
String fromUnit, String toUnit)
{

try {
SOAP_ACTION = namespace + MethodName;

//Adding values to request object
request = new SoapObject(namespace, MethodName);

//Adding Double value to request object
PropertyInfo weightProp =new PropertyInfo();
weightProp.setName("Weight");
weightProp.setValue(weight);
weightProp.setType(double.class);
request.addProperty(weightProp);

//Adding String value to request object
request.addProperty("FromUnit", "" + fromUnit);
request.addProperty("ToUnit", "" + toUnit);

SetEnvelope();

try {

//SOAP calling webservice
androidHttpTransport.call(SOAP_ACTION, envelope);

//Got Webservice response
String result = envelope.getResponse().toString();

return result;

} catch (Exception e) {
// TODO: handle exception
return e.toString();
}
} catch (Exception e) {
// TODO: handle exception
return e.toString();
}
}
}


My updated Activity code :

public class CheckDNLoginActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

final Button webserviceCallButton = (Button) findViewById(R.id.webservice);
final TextView webserviceResponse = (TextView) findViewById(R.id.webserviceResponse);

webserviceCallButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {

webserviceResponse.setText("Requesting to server .....");

new ExecuteService().execute();

}
});
}


class ExecuteService extends AsyncTask<String, Void, String> {

@Override
protected String doInBackground(String... params) {
//Create Webservice class object
WebService com = new WebService();

// Initialize variables
String weight = "18000";
String fromUnit = "Grams";
String toUnit = "Kilograms";

//Call Webservice class method and pass values and get response
String aResponse = com.getConvertedWeight("ConvertWeight", weight, fromUnit, toUnit);

//Alert message to show webservice response
Toast.makeText(getApplicationContext(), weight+" Gram= "+aResponse+" Kilograms",
Toast.LENGTH_LONG).show();

Log.i("AndroidExampleOutput", "----"+aResponse);
return aResponse;
}

@Override
protected void onPostExecute(String result) {
webserviceResponse.setText("Response : "+ result);

}

@Override
protected void onPreExecute() {}
}
}


This is my updated logcat . When i run my application i got an error:,

FATAL EXCEPTION: main
Process: com.example.dell.piechart2, PID: 2762
java.lang.NullPointerException
at com.example.dell.piechart2.CheckDNLoginActivity$ExecuteService.onPostExecute(CheckDNLoginActivity.java:63)
at com.example.dell.piechart2.CheckDNLoginActivity$ExecuteService.onPostExecute(CheckDNLoginActivity.java:38)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)


What is the problem? Please help me. I post my full logcat here. you can also check it.
Thanks in advance.

Answer Source

You need to use Async Task class as below,

First change your button click event by below

  webserviceCallButton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {

            webserviceResponse.setText("Requesting to server .....");

            new ExecuteService().execute();

        }
    });

Now, check below your entire activity code

    public class CheckDNLoginActivity extends Activity {

        Button webserviceCallButton;
        TextView webserviceResponse;

        @Override
        protected void onCreate(Bundle savedInstanceState) {

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

            webserviceCallButton = (Button) findViewById(R.id.webservice);
            webserviceResponse = (TextView) findViewById(R.id.webserviceResponse);

            webserviceCallButton.setOnClickListener(new OnClickListener() {
                public void onClick(View v) {

                    webserviceResponse.setText("Requesting to server .....");

                    new ExecuteService().execute();

                 }
             });
         }


     class ExecuteService extends AsyncTask<String, Void, String> {

            @Override
            protected String doInBackground(String... params) {
                //Create Webservice class object
                WebService com = new WebService();

                // Initialize variables
                String weight   = "18000";
                String fromUnit = "Grams";
                String toUnit   = "Kilograms";

                //Call Webservice class method and pass values and get response
                String aResponse = com.getConvertedWeight("ConvertWeight", weight, fromUnit, toUnit);

                //Alert message to show webservice response
                Toast.makeText(getApplicationContext(), weight+" Gram= "+aResponse+" Kilograms",
                    Toast.LENGTH_LONG).show();

                Log.i("AndroidExampleOutput", "----"+aResponse);
                return aResponse;
            }

            @Override
            protected void onPostExecute(String result) {
                webserviceResponse.setText("Response : "+ result);

            }

            @Override
            protected void onPreExecute() {}
        }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download