Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call .NET web service in Android

My .NET web service returns an XML. When I call the web service with ksoap2 in Android, I have this issue. Please help.

My Logcat in Eclipse

12-19 15:58:11.951: W/dalvikvm(2041): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
12-19 15:58:11.961: E/AndroidRuntime(2041): FATAL EXCEPTION: main
12-19 15:58:11.961: E/AndroidRuntime(2041): java.lang.RuntimeException: double ID
12-19 15:58:11.961: E/AndroidRuntime(2041):     at org.ksoap2.serialization.SoapSerializationEnvelope.read(SoapSerializationEnvelope.java:407)
12-19 15:58:11.961: E/AndroidRuntime(2041):     at org.ksoap2.serialization.SoapSerializationEnvelope.readUnknown(SoapSerializationEnvelope.java:273)
12-19 15:58:11.961: E/AndroidRuntime(2041):     at org.ksoap2.serialization.SoapSerializationEnvelope.read(SoapSerializationEnvelope.java:389)
12-19 15:58:11.961: E/AndroidRuntime(2041):     at org.ksoap2.serialization.SoapSerializationEnvelope.readUnknown(SoapSerializationEnvelope.java:273)
12-19 15:58:11.961: E/AndroidRuntime(2041):     at org.ksoap2.serialization.SoapSerializationEnvelope.read(SoapSerializationEnvelope.java:389)
12-19 15:58:11.961: E/AndroidRuntime(2041):     at org.ksoap2.serialization.SoapSerializationEnvelope.readUnknown(SoapSerializationEnvelope.java:273)
12-19 15:58:11.961: E/AndroidRuntime(2041):     at org.ksoap2.serialization.SoapSerializationEnvelope.read(SoapSerializationEnvelope.java:389)
12-19 15:58:11.961: E/AndroidRuntime(2041):     at org.ksoap2.serialization.SoapSerializationEnvelope.parseBody(SoapSerializationEnvelope.java:151)
12-19 15:58:11.961: E/AndroidRuntime(2041):     at org.ksoap2.SoapEnvelope.parse(SoapEnvelope.java:140)
12-19 15:58:11.961: E/AndroidRuntime(2041):     at org.ksoap2.transport.Transport.parseResponse(Transport.java:116)
12-19 15:58:11.961: E/AndroidRuntime(2041):     at org.ksoap2.transport.HttpTransportSE.call(HttpTransportSE.java:259)
12-19 15:58:11.961: E/AndroidRuntime(2041):     at org.ksoap2.transport.HttpTransportSE.call(HttpTransportSE.java:114)
12-19 15:58:11.961: E/AndroidRuntime(2041):     at com.example.webservicee.MainActivity$1.onClick(MainActivity.java:133)
12-19 15:58:11.961: E/AndroidRuntime(2041):     at android.view.View.performClick(View.java:2408)
12-19 15:58:11.961: E/AndroidRuntime(2041):     at android.view.View$PerformClick.run(View.java:8816)
12-19 15:58:11.961: E/AndroidRuntime(2041):     at android.os.Handler.handleCallback(Handler.java:587)
12-19 15:58:11.961: E/AndroidRuntime(2041):     at android.os.Handler.dispatchMessage(Handler.java:92)
12-19 15:58:11.961: E/AndroidRuntime(2041):     at android.os.Looper.loop(Looper.java:123)
12-19 15:58:11.961: E/AndroidRuntime(2041):     at android.app.ActivityThread.main(ActivityThread.java:4627)
12-19 15:58:11.961: E/AndroidRuntime(2041):     at java.lang.reflect.Method.invokeNative(Native Method)
12-19 15:58:11.961: E/AndroidRuntime(2041):     at java.lang.reflect.Method.invoke(Method.java:521)
12-19 15:58:11.961: E/AndroidRuntime(2041):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
12-19 15:58:11.961: E/AndroidRuntime(2041):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)

MainActivity.java

package com.example.webservicee; 
import java.io.IOException;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.SoapFault;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
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 {

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

    final static String METHOD_NAME = "GetContent";

    final static String SOAP_ACTION = "http://tempuri.org/GetContent";

    final static String URL = "http://www.example.com/XMLGenerator/GenerateXML.asmx";


    private Button Mybtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        deger = (EditText) findViewById(R.id.deger);
        sonuc = (TextView) findViewById(R.id.flag);
        Mybtn = (Button) findViewById(R.id.hesapla);
        Mybtn.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                // TODO Auto-generated method stub
                SoapObject Request = new SoapObject(NAMESPACE, METHOD_NAME);

                //My webservice paramaters 
                Request.addProperty("SectionsInclude","10");
                Request.addProperty("DocumentCount",10);
                Request.addProperty("SortBy","0");
                Request.addProperty("SortOrder","ASC");
                Request.addProperty("UserName","myuser");
                Request.addProperty("Pass","Lsss");
                /**/
                      /*  PropertyInfo pi=new PropertyInfo();
                        pi.setName("arg0");
                        pi.setValue("10");
                        pi.setType(String.class);
                        Request.addProperty(pi);
                        pi=new PropertyInfo();


                        pi.setName("arg1");
                        pi.setValue(10);
                        pi.setType(Integer.class);
                        Request.addProperty(pi);
                        pi=new PropertyInfo();


                        pi.setName("arg2");
                        pi.setValue("0");
                        pi.setType(String.class);
                        Request.addProperty(pi);
                        pi=new PropertyInfo();


                        pi.setName("arg3");
                        pi.setValue("ASC");
                        pi.setType(String.class);
                        Request.addProperty(pi);
                        pi=new PropertyInfo();

                        pi.setName("arg4");
                        pi.setValue("myuser");
                        pi.setType(String.class);
                        Request.addProperty(pi);
                        pi=new PropertyInfo();


                        pi.setName("arg5");
                        pi.setValue("Lsss");
                        pi.setType(String.class);
                        Request.addProperty(pi);


                        */


                SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
                soapEnvelope.dotNet = true;
                soapEnvelope.setOutputSoapObject(Request);
                //soapEnvelope.bodyOut = Request;
                HttpTransportSE aht = new HttpTransportSE(URL);
                try {
                    aht.call(SOAP_ACTION, soapEnvelope);


                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (XmlPullParserException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                String result;
                try {

                    result = "Fahrenheit:"+(SoapPrimitive) soapEnvelope.getResponse();
                     Log.d("--Result-- ", result);
                    //sonuc.setText(result);

                    } catch (SoapFault e) 
                    {

                    e.printStackTrace();

                    }
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

}

This is the example response xml:

<?xml version="1.0" encoding="utf-8"?>
<liste>
<document id="6" titles="bestPeople" showingDate="27.09.2011 00:00:00"  date="27.09.2011 00:00:00" ContentID=rbHe8zKvDTG7TLS" >
<part id="6" baslik="best" icerik="&lt;table style=&quot;width: 188px; height: 24px;&quot; border=&quot;tbody&gt;&#xD;&#xA;&lt;/table&gt;" resim="">
<SecNotes><![CDATA[]]></SecNotes>
<ContNotes><![CDATA[]]></ContNotes>
</part>
<SecNotes><![CDATA[]]></SecNotes>
<ContNotes><![CDATA[]]></ContNotes>
</document>
</liste>
like image 746
Erhan Demirci Avatar asked Dec 19 '12 16:12

Erhan Demirci


3 Answers

I solve it. I added this code. it's working.

my Code

@Override
protected void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    init();
}
private void init()
{
    //your webservice envelope
    String envelope="<?xml version=\"1.0\" encoding=\"utf-8\"?><soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"><soap:Body><GetContentTreeBySections xmlns=\"http://tempuri.org/\"><SectionsInclude>%s</SectionsInclude><DocumentCount>%s</DocumentCount><SortBy>%s</SortBy><SortOrder>%s</SortOrder><UserName>%s</UserName><Pass>%s</Pass></GetContentTreeBySections></soap:Body></soap:Envelope>";

    String myEnvelope = String.format(envelope, "myParam1 value", "myParam2 value","myParam3 value","myParam4 value");
    String url = "http://www.mywebserice.com/XMLGenerator/GenerateXML.asmx";
    String soapAction = "http://tempuri.org/GetContentTreeBySections"; 
    String response = CallWebService(url, soapAction, myEnvelope);
    //Log.v("response", response);
    Toast.makeText(getApplicationContext(), "this"+response,Toast.LENGTH_LONG).show();
    String xml=response;    
}

@Override
public boolean onCreateOptionsMenu(Menu menu) 
{
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}
String CallWebService(String url,String soapAction,String envelope) 
{

      final DefaultHttpClient httpClient=new DefaultHttpClient();
      // request parameters
      HttpParams params = httpClient.getParams();
         HttpConnectionParams.setConnectionTimeout(params, 10000);
         HttpConnectionParams.setSoTimeout(params, 15000);
         // set parameter
      HttpProtocolParams.setUseExpectContinue(httpClient.getParams(), true);

      // POST the envelope
      HttpPost httppost = new HttpPost(url);
      // add headers
         httppost.setHeader("soapaction", soapAction);
         httppost.setHeader("Content-Type", "text/xml; charset=utf-8");
         String responseString="";

         try 
         {
                // the entity holds the request
                HttpEntity entity = new StringEntity(envelope);
                httppost.setEntity(entity);

                // Response handler
                ResponseHandler<String> rh=new ResponseHandler<String>() {
        // invoked when client receives response
        public String handleResponse(HttpResponse response)
          throws ClientProtocolException, IOException {

         // get response entity
         HttpEntity entity = response.getEntity();

         // read the response as byte array
               StringBuffer out = new StringBuffer();
               byte[] b = EntityUtils.toByteArray(entity);

               // write the response byte array to a string buffer
               out.append(new String(b, 0, b.length));
               return out.toString();
        }
       };

       responseString=httpClient.execute(httppost, rh); 

      }
         catch (Exception e) {
          Log.v("exception", e.toString());
      }

         // close the connection
      httpClient.getConnectionManager().shutdown();
      return responseString;
}
like image 191
Erhan Demirci Avatar answered Nov 19 '22 07:11

Erhan Demirci


First of all never use Network Operations in main thread try always to insert network operations inside non-main thread like AsyncTask or any other worker thread. Second use the following code to get the result:

 String message="";
    SoapObject result = (SoapObject)envelope.bodyIn;
    if(result != null)
       {
          message=result.getProperty(0).toString();
       }

and also change the following code

Request.addProperty("DocumentCount",10);

to be

Request.addProperty("DocumentCount","10");
like image 1
Husam A. Al-ahmadi Avatar answered Nov 19 '22 07:11

Husam A. Al-ahmadi


Rather than using ksoap, try using ice-soap library, which is open source. It's far better than ksoap and provides efficient library to send request and parse response using annotatations....

like image 2
Vipul Narkhede Avatar answered Nov 19 '22 07:11

Vipul Narkhede