Calling a web service from Android

Put your problem here if it does not fit any of the other categories.

Postby mcrofut » Mon Jan 18, 2010 11:58 pm

I am invoking a .NET Web Service and was having problems with the SoapObject parameters not going across in the call (all parameters were null in .NET). dp's advice:

envelope.dotNet = true


fixed the problem for me. Thank you.
mcrofut
Once Poster
Once Poster
 
Posts: 1
Joined: Mon Jan 18, 2010 11:54 pm

Top

Parameters not passing when access a java web service

Postby roshansn » Fri Feb 12, 2010 1:41 pm

I am calling a java web service. But parameters not passing even the expecting method is fired. is there any property to set to pass the parameters in java?

Roshan
roshansn
Once Poster
Once Poster
 
Posts: 1
Joined: Fri Feb 12, 2010 1:38 pm

Postby Bigbacon » Sun Feb 21, 2010 3:49 pm

I cant get this to work either iwth a .NEt 3.5 web service running on android 1.5

My webservice is working correctly and it only returns a string and does not take parameters.

http://www.anddev.org/viewtopic.php?p=36170#36170
Bigbacon
Junior Developer
Junior Developer
 
Posts: 13
Joined: Mon Jan 18, 2010 1:43 pm

Postby mrfalafel » Wed Feb 24, 2010 1:11 am

Hope this helps

http://www.vimeo.com/9633556

Thanks
-Lino
mrfalafel
Freshman
Freshman
 
Posts: 4
Joined: Sun Feb 21, 2010 11:12 pm
Location: San Jose, CA

Postby junejar » Wed Mar 31, 2010 10:08 am

Hi
I am not able to run a very basic client programme using ksoap. Code posted below. Application force closes. On debug, this line is the culprit androidHttpTransport.call(
Any help appreciated.

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.AndroidHttpTransport;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;

public class Sample extends Activity {

private static final String SOAP_ACTION = "getCurrentPosition";
private static final String METHOD_NAME = "getCurrentPosition";
private static final String NAMESPACE = "";
private static final String URL = "http://192.168.56.1:8080/axis/NHLService.jws";

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

setContentView(R.layout.main);
findViewById(R.id.cmdCalculate).setOnClickListener(new OnClickListener() {
public void onClick(View view) {
((TextView)findViewById(R.id.lblStatus)).setText("... Invoking Web Service ...");
String a = "central";
String b = "chicago";

SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("division", a);
request.addProperty("team", b);

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
AndroidHttpTransport androidHttpTransport = new AndroidHttpTransport (URL);

try {
androidHttpTransport.call(SOAP_ACTION, envelope);
Object result = envelope.getResponse();
((TextView)findViewById(R.id.lblStatus)).setText(result.toString());
} catch(Exception e) {
e.printStackTrace();
}
} // on click ends
});//listner ends
}//on create ends
}//end
junejar
Once Poster
Once Poster
 
Posts: 1
Joined: Wed Mar 31, 2010 9:56 am

Re: Calling a web service from Android

Postby dj_4war » Fri Apr 16, 2010 5:38 am

Hello Lex...

could u pls give me the code for servlet implementation for this same code....



Lex wrote:Hi,
Im trying to receive data from a Web Service. I'm using KSOAP2. Here's my code
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. package com.google.android.Test;
  2.  
  3.  
  4. import org.ksoap2.SoapEnvelope;
  5. import org.ksoap2.serialization.SoapObject;
  6. import org.ksoap2.serialization.SoapSerializationEnvelope;
  7. import org.ksoap2.transport.HttpTransport;
  8.  
  9. import android.app.Activity;
  10. import android.os.Bundle;
  11. import android.widget.TextView;
  12.  
  13. public class myWebService extends Activity
  14. {
  15.          private static final String SOAP_ACTION = "HelloYou";
  16.      private static final String METHOD_NAME = "getHello";
  17.      private static final String NAMESPACE = "urn:HelloYou";
  18.      private static final String URL = "http://localhost/lab/service.php";
  19.      private Object resultRequestSOAP = null;
  20.      
  21.             @Override
  22.             public void onCreate(Bundle icicle)
  23.             {
  24.                 super.onCreate(icicle);
  25.                 TextView tv = new TextView(this);
  26.                 setContentView(tv);
  27.                
  28.  
  29.             SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
  30.  
  31.  
  32.              //SoapObject
  33.             request.addProperty("firstname", "John");
  34.             request.addProperty("lastname", "Williams");
  35.             SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
  36.             envelope.setOutputSoapObject(request);
  37.            
  38.  
  39.             HttpTransport androidHttpTransport = new HttpTransport(URL);
  40.             try
  41.             {
  42.                 androidHttpTransport.call(SOAP_ACTION, envelope);
  43.                 resultsRequestSOAP =  envelope.getResponse();
  44.                 String[] results = (String[])  resultsRequestSOAP;
  45.                 tv.setText( results[0]);
  46.             }
  47.             catch (Exception aE)
  48.             {
  49.                 aE.printStackTrace ();;
  50.             }
  51.            }
  52. }
Parsed in 0.037 seconds, using GeSHi 1.0.8.4


I'm getting an Error because the IO/Connector is missing ? Is there any other way to retrieve data from a webservice then ?
dj_4war
Junior Developer
Junior Developer
 
Posts: 10
Joined: Thu Apr 01, 2010 7:49 am

Top

Postby w00tfest99 » Mon Apr 26, 2010 10:47 pm

mrfalafel wrote:Hope this helps

http://www.vimeo.com/9633556

Thanks
-Lino


This helped me quite a bit but I was hoping someone could help me with the error I'm getting. I followed the code exactly as described in the video but when I call "getResponse()" I just get the word "error". There's no exception thrown or any additional information about the error. In the comments on the video I, someone mentioned that this was caused by using NetBeans and not having the buildpath setup correctly. But I'm just using Eclipse. Is there something I'm missing? Code is below:

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. String SOAP_ACTION="http://tempuri.org/CelsiusToFahrenheit";
  2. String METHOD_NAME = "CelsiusToFahrenheit";
  3. String NAMESPACE = "http://tempuri.org";
  4. String URL = "http://w3schools.com/webservices/tempconvert.asmx";
  5.                
  6. SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
  7. PropertyInfo pi = new PropertyInfo();
  8. pi.setName("Celsius");
  9. pi.setValue("32");
  10. request.addProperty(pi);
  11.                
  12. SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
  13. envelope.dotNet = true;
  14. envelope.setOutputSoapObject(request);
  15.                
  16. HttpTransportSE aht = new HttpTransportSE(URL);
  17.                
  18. try
  19. {
  20.         aht.call(SOAP_ACTION, envelope);
  21.         SoapPrimitive results = (SoapPrimitive)envelope.getResponse();
  22. }
  23. catch (Exception e)
  24. {
  25.         e.printStackTrace();
  26. }
  27.  
Parsed in 0.034 seconds, using GeSHi 1.0.8.4
w00tfest99
Once Poster
Once Poster
 
Posts: 1
Joined: Mon Apr 26, 2010 10:41 pm

Re: Calling a web service from Android

Postby DoM » Wed May 19, 2010 5:45 pm

Hi everyone,I'm programming an application who must do some request to a WebServices this is my code
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. public class Client extends Activity
  2. {
  3.  
  4.        
  5.            
  6.           private String SOAP_ACTION = "http://WSGeoEAR-WSGeoServer/getAllPositions";
  7.           private String METHOD_NAME = "getAllPositions";
  8.           private String NAMESPACE = "http://WSGeoEAR-WSGeoServer/";
  9.           private static final String URL ="http://192.41.218.56:8080/WSGeoEAR-WSGeoServer/NavFinderBean?WSDL";
  10.          
  11.          
  12.               /** Called when the activity is first created. */
  13.               @Override
  14.               public void onCreate(Bundle icicle) {
  15.                   super.onCreate(icicle);
  16.                   setContentView(R.layout.main);
  17.                
  18.                   ((TextView)findViewById(R.id.lblStatus)).setText("1");  
  19.  
  20.                 //Chiamo il Metodo del WebServer
  21.                  SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
  22.                  /*SoapObject parameters = new SoapObject(NAMESPACE,"getAllPositionsResponse");          
  23.                  parameters.addProperty("idUtente",1);
  24.                  request.addProperty(METHOD_NAME,parameters);    
  25.              */
  26.                   request.addProperty("idUtente",1);
  27.                    
  28.                   SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
  29.                   envelope.dotNet = true;
  30.                   envelope.setOutputSoapObject(request);
  31.              
  32.            
  33.                   HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
  34.            
  35.                
  36.                   try {
  37.                   androidHttpTransport.call(SOAP_ACTION, envelope);
  38.                  
  39.                   //Prende la risposta SOAP e ne estrae il corpo
  40.                   SoapObject resultsRequestSOAP = (SoapObject) envelope.bodyIn;
  41.                  
  42.                   ArrayList<Position> resultData = (ArrayList<Position>)resultsRequestSOAP.getProperty("getAllPositionsResponse");
  43.                
  44.                   for(Position p : resultData)
  45.                   {
  46.                          
  47.                       ((TextView)findViewById(R.id.lblStatus)).setText(p.getAllInformation());  
  48.                   }        
  49.                         } catch(Exception E) {
  50.                               ((TextView)findViewById(R.id.lblStatus)).setText("ERROR:" + E.getClass().getName() + ": " + E.getMessage());
  51.                             }
  52.                           }
  53.                                  
  54.                   }
Parsed in 0.042 seconds, using GeSHi 1.0.8.4
:

I also created a class Position
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. public class Position  implements java.io.Serializable {
  2.     private long idPosition;
  3.  
  4.     private int idUtente;
  5.  
  6.     private double latitudine;
  7.  
  8.     private double longitudine;
  9.  
  10.     private long timeInserted;
  11.  
  12.     public Position() {
  13.     }
  14.  
  15.     public Position(
  16.            long idPosition,
  17.            int idUtente,
  18.            double latitudine,
  19.            double longitudine,
  20.            long timeInserted) {
  21.            this.idPosition = idPosition;
  22.            this.idUtente = idUtente;
  23.            this.latitudine = latitudine;
  24.            this.longitudine = longitudine;
  25.            this.timeInserted = timeInserted;
  26.     }
  27.  
  28.  
  29.     /**
  30.      * Gets the idPosition value for this Position.
  31.      *
  32.      * @return idPosition
  33.      */
  34.     public long getIdPosition() {
  35.         return idPosition;
  36.     }
  37.  
  38.  
  39.     /**
  40.      * Sets the idPosition value for this Position.
  41.      *
  42.      * @param idPosition
  43.      */
  44.     public void setIdPosition(long idPosition) {
  45.         this.idPosition = idPosition;
  46.     }
  47.  
  48.  
  49.     /**
  50.      * Gets the idUtente value for this Position.
  51.      *
  52.      * @return idUtente
  53.      */
  54.     public int getIdUtente() {
  55.         return idUtente;
  56.     }
  57.  
  58.  
  59.     /**
  60.      * Sets the idUtente value for this Position.
  61.      *
  62.      * @param idUtente
  63.      */
  64.     public void setIdUtente(int idUtente) {
  65.         this.idUtente = idUtente;
  66.     }
  67.  
  68.  
  69.     /**
  70.      * Gets the latitudine value for this Position.
  71.      *
  72.      * @return latitudine
  73.      */
  74.     public double getLatitudine() {
  75.         return latitudine;
  76.     }
  77.  
  78.  
  79.     /**
  80.      * Sets the latitudine value for this Position.
  81.      *
  82.      * @param latitudine
  83.      */
  84.     public void setLatitudine(double latitudine) {
  85.         this.latitudine = latitudine;
  86.     }
  87.  
  88.  
  89.     /**
  90.      * Gets the longitudine value for this Position.
  91.      *
  92.      * @return longitudine
  93.      */
  94.     public double getLongitudine() {
  95.         return longitudine;
  96.     }
  97.  
  98.  
  99.     /**
  100.      * Sets the longitudine value for this Position.
  101.      *
  102.      * @param longitudine
  103.      */
  104.     public void setLongitudine(double longitudine) {
  105.         this.longitudine = longitudine;
  106. }
  107. }
  108.  
Parsed in 0.042 seconds, using GeSHi 1.0.8.4


and this is my emulator response:
STATUS:
ERROR:org.xmlpull.v1.XmlPullParserException;expected:END_TAG{http://scemas.xmlsoap.org/soap/envelope/}Body(position:END_TAG</{http://schemas.xmlsoap.org/soap/envelope/}env:Fault>@1:371 in java.io.InputStreamReader@43d1d360)

Can you help me??
DoM
Freshman
Freshman
 
Posts: 9
Joined: Mon Mar 16, 2009 12:43 pm

Re:

Postby oudomvilla » Sat Aug 14, 2010 7:29 pm

Hi, I am very new to Android, I have one project to do now. I want to access to Local Web Server from Android. I currently using WampServer, I tested your code, it says " localhost/127.0.0.1:80 Connection Refused" < could you please tell me what requirement should I do to for Android Emulator to access web server?
Thanks
oudomvilla
Once Poster
Once Poster
 
Posts: 1
Joined: Fri Aug 13, 2010 4:29 am

Re: Calling a web service from Android

Postby PrashantAdesara » Sat Aug 28, 2010 7:48 am

Hello Friends,
Myself Prashant.

Me giving u WebService Example for Android.

Part - 1:
In this part I giving small demo for webservice running in Android device.
From this link you can find this example. Where I give Comment for webservice demo.
Please all of you check it.
http://lukencode.com/2010/04/27/calling ... omment-179

Part - 2: Webservice running in Android with database connectivity
Now I am running database connectivity and return value from database and showing in Android device.
Here i m using Microsoft SQL connectivity. You can use your way.
For that u have to download this file
SQL connectivity jar file for webservice:
http://www.4shared.com/file/IxoPooiE/sqljdbc.html
Ksoap Library File for android project.
http://www.4shared.com/file/uOhx5aoj/ks ... 4-jar.html

This is good example for you all.

First We create Dynamic Project usign Eclipse
Add this package and class.
Package Name: org.webservice.pa
Class Name : GetDatabaseRecords.java
and also create once class for bean.(Setter-Getter Property).
Class Name : BookData.java


BookData.java

package org.webservice.pa;

public class BookData {
public String bookCode;
public String bookName;
public String authorName;

public String getBookCode() {
return bookCode;
}
public void setBookCode(String bookCode) {
this.bookCode = bookCode;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public String getAuthorName() {
return authorName;
}
public void setAuthorName(String authorName) {
this.authorName = authorName;
}

}


GetDatabaseRecords.java

package org.webservice.pa;
public class GetDatabaseRecords{

public BookData[] getBookDetails{
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
ArrayList<BookData> bookDataList = new ArrayList<BookData>();
BookData bookData = null;
try
{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");//Driver Name
con = DriverManager.getConnection("connectionUrl");//connection URL
stmt = con.createStatement();
rs = stmt.executeQuery("select * from BookDetails");//Table Name
while (rs.next())
{
bookData= new BookData();
bookData.setBookCode(rs.getString("bookCode"));
bookData.setBookName(rs.getString("bookName"));
bookData.setAuthorName(rs.getString("authorName"));
bookDataList.add(bookData);
}
}catch (Exception e)
{
e.printStackTrace();
}
finally {
try {
rs.close();
} catch(Exception e) {}
try {
stmn.close();
} catch(Exception e) {}
try {
con.close();
} catch(Exception e) {}
}
return (BookData[])bookDataList.toArray(new BookData[bookDataList.size()]);
}
}

Now Right click on GetDatabaseRecords.java file and select "WebService" option.
Now further step is same as posted my Part 1:
Click finish.
and test your service it will return BookData object.
Here our Dynamic WebProject task is completed.


Now you want to create Android Project for calling above WebService.
Now u add "ksoap" library File in android project:
Download from here:
http://www.4shared.com/file/uOhx5aoj/ks ... 4-jar.html

public class MainActivity extends Activity {
private String METHOD_NAME = "getBookDetails"; // our webservice method name
private String NAMESPACE = "http://pa.webservice.org"; // Here package name in webservice with reverse order.
private String SOAP_ACTION = NAMESPACE + METHOD_NAME; // NAMESPACE + method name
private static final String URL = "http://192.168.1.1:8080/WebServiceDemo/services/GetDatabaseRecords?wsdl"; // you must use ipaddress here, don't use Hostname or localhost

public void onCreate(Bundle icicle)
{
super.onCreate(icicle);
setContentView(R.layout.main);
TextView tv = (TextView) findViewById(R.id.txtsearch);
try
{
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
androidHttpTransport.call(SOAP_ACTION,envelope);
SoapObect so = (SoapObject)envelope.bodyIn;

System.out.println("Counter: "+so.getPropertyCount());

for(int i =0; i < so.getPropertyCount(); i++){
SoapObject soap = (SoapObject) so.getProperty(i);
System.out.println("BookCode :: "+ soap.getProperty("bookCode"));
System.out.println("BookName :: "+ soap.getProperty("bookName"));
System.out.println("AuthorName :: "+ soap.getProperty("authorName"));
}

tv.setText(so.toString());
} catch (Exception E) {
E.printStackTrace();
tv.setText("ERROR:" + E.getClass().getName() + ": " + E.getMessage());
}
}
}


Now you can run your project and it's work fine
:)

And if you have any doubt just tell me.


Thanks & Regards,
Prashant Adesara.
PrashantAdesara
Freshman
Freshman
 
Posts: 6
Joined: Sat Aug 28, 2010 7:24 am

Re:

Postby PrashantAdesara » Sat Aug 28, 2010 7:56 am

junejar wrote:Hi
I am not able to run a very basic client programme using ksoap. Code posted below. Application force closes. On debug, this line is the culprit androidHttpTransport.call(
Any help appreciated.

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.AndroidHttpTransport;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;

public class Sample extends Activity {

private static final String SOAP_ACTION = "getCurrentPosition";
private static final String METHOD_NAME = "getCurrentPosition";
private static final String NAMESPACE = "";
private static final String URL = "http://192.168.56.1:8080/axis/NHLService.jws";

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

setContentView(R.layout.main);
findViewById(R.id.cmdCalculate).setOnClickListener(new OnClickListener() {
public void onClick(View view) {
((TextView)findViewById(R.id.lblStatus)).setText("... Invoking Web Service ...");
String a = "central";
String b = "chicago";

SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("division", a);
request.addProperty("team", b);

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
AndroidHttpTransport androidHttpTransport = new AndroidHttpTransport (URL);

try {
androidHttpTransport.call(SOAP_ACTION, envelope);
Object result = envelope.getResponse();
((TextView)findViewById(R.id.lblStatus)).setText(result.toString());
} catch(Exception e) {
e.printStackTrace();
}
} // on click ends
});//listner ends
}//on create ends
}//end



Hello Friends,
Myself Prashant.

Me giving u WebService Example for Android.

Part - 1:
In this part I giving small demo for webservice running in Android device.
From this link you can find this example. Where I give Comment for webservice demo.
Please all of you check it.
http://lukencode.com/2010/04/27/calling ... omment-179

Part - 2: Webservice running in Android with database connectivity
Now I am running database connectivity and return value from database and showing in Android device.
Here i m using Microsoft SQL connectivity. You can use your way.
For that u have to download this file
SQL connectivity jar file for webservice:
http://www.4shared.com/file/IxoPooiE/sqljdbc.html
Ksoap Library File for android project.
http://www.4shared.com/file/uOhx5aoj/ks ... 4-jar.html

This is good example for you all.

First We create Dynamic Project usign Eclipse
Add this package and class.
Package Name: org.webservice.pa
Class Name : GetDatabaseRecords.java
and also create once class for bean.(Setter-Getter Property).
Class Name : BookData.java


BookData.java

package org.webservice.pa;

public class BookData
{

public String bookCode;
public String bookName;
public String authorName;

public String getBookCode() {
return bookCode;
}
public void setBookCode(String bookCode) {
this.bookCode = bookCode;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public String getAuthorName() {
return authorName;
}
public void setAuthorName(String authorName) {
this.authorName = authorName;
}

}


GetDatabaseRecords.java

package org.webservice.pa;

public class GetDatabaseRecords
{

public BookData[] getBookDetails{
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
ArrayList<BookData> bookDataList = new ArrayList<BookData>();
BookData bookData = null;
try
{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");//Driver Name
con = DriverManager.getConnection("connectionUrl");//connection URL
stmt = con.createStatement();
rs = stmt.executeQuery("select * from BookDetails");//Table Name
while (rs.next())
{
bookData= new BookData();
bookData.setBookCode(rs.getString("bookCode"));
bookData.setBookName(rs.getString("bookName"));
bookData.setAuthorName(rs.getString("authorName"));
bookDataList.add(bookData);
}
}catch (Exception e)
{
e.printStackTrace();
}
finally {
try {
rs.close();
} catch(Exception e) {}
try {
stmn.close();
} catch(Exception e) {}
try {
con.close();
} catch(Exception e) {}
}
return (BookData[])bookDataList.toArray(new BookData[bookDataList.size()]);
}
}

Now Right click on GetDatabaseRecords.java file and select "WebService" option.
Now further step is same as posted my Part 1:
Click finish.
and test your service it will return BookData object.
Here our Dynamic WebProject task is completed.


Now you want to create Android Project for calling above WebService.
Now u add "ksoap" library File in android project:
Download from here:
http://www.4shared.com/file/uOhx5aoj/ks ... 4-jar.html

public class MainActivity extends Activity {
private String METHOD_NAME = "getBookDetails"; // our webservice method name
private String NAMESPACE = "http://pa.webservice.org"; // Here package name in webservice with reverse order.
private String SOAP_ACTION = NAMESPACE + METHOD_NAME; // NAMESPACE + method name
private static final String URL = "http://192.168.1.1:8080/WebServiceDemo/services/GetDatabaseRecords?wsdl"; // you must use ipaddress here, don't use Hostname or localhost

public void onCreate(Bundle icicle)
{
super.onCreate(icicle);
setContentView(R.layout.main);
TextView tv = (TextView) findViewById(R.id.txtsearch);
try
{
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
androidHttpTransport.call(SOAP_ACTION,envelope);
SoapObect so = (SoapObject)envelope.bodyIn;

System.out.println("Counter: "+so.getPropertyCount());

for(int i =0; i < so.getPropertyCount(); i++){
SoapObject soap = (SoapObject) so.getProperty(i);
System.out.println("BookCode :: "+ soap.getProperty("bookCode"));
System.out.println("BookName :: "+ soap.getProperty("bookName"));
System.out.println("AuthorName :: "+ soap.getProperty("authorName"));
}

tv.setText(so.toString());
} catch (Exception E) {
E.printStackTrace();
tv.setText("ERROR:" + E.getClass().getName() + ": " + E.getMessage());
}
}
}


Now you can run your project and it's work fine
:)

And if you have any doubt just tell me.


Thanks & Regards,
Prashant Adesara.
PrashantAdesara
Freshman
Freshman
 
Posts: 6
Joined: Sat Aug 28, 2010 7:24 am

Re: Calling a web service from Android

Postby PrashantAdesara » Sat Aug 28, 2010 7:57 am

Lex wrote:Hi,
Im trying to receive data from a Web Service. I'm using KSOAP2. Here's my code
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. package com.google.android.Test;
  2.  
  3.  
  4. import org.ksoap2.SoapEnvelope;
  5. import org.ksoap2.serialization.SoapObject;
  6. import org.ksoap2.serialization.SoapSerializationEnvelope;
  7. import org.ksoap2.transport.HttpTransport;
  8.  
  9. import android.app.Activity;
  10. import android.os.Bundle;
  11. import android.widget.TextView;
  12.  
  13. public class myWebService extends Activity
  14. {
  15.          private static final String SOAP_ACTION = "HelloYou";
  16.      private static final String METHOD_NAME = "getHello";
  17.      private static final String NAMESPACE = "urn:HelloYou";
  18.      private static final String URL = "http://localhost/lab/service.php";
  19.      private Object resultRequestSOAP = null;
  20.      
  21.             @Override
  22.             public void onCreate(Bundle icicle)
  23.             {
  24.                 super.onCreate(icicle);
  25.                 TextView tv = new TextView(this);
  26.                 setContentView(tv);
  27.                
  28.  
  29.             SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
  30.  
  31.  
  32.              //SoapObject
  33.             request.addProperty("firstname", "John");
  34.             request.addProperty("lastname", "Williams");
  35.             SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
  36.             envelope.setOutputSoapObject(request);
  37.            
  38.  
  39.             HttpTransport androidHttpTransport = new HttpTransport(URL);
  40.             try
  41.             {
  42.                 androidHttpTransport.call(SOAP_ACTION, envelope);
  43.                 resultsRequestSOAP =  envelope.getResponse();
  44.                 String[] results = (String[])  resultsRequestSOAP;
  45.                 tv.setText( results[0]);
  46.             }
  47.             catch (Exception aE)
  48.             {
  49.                 aE.printStackTrace ();;
  50.             }
  51.            }
  52. }
Parsed in 0.042 seconds, using GeSHi 1.0.8.4


I'm getting an Error because the IO/Connector is missing ? Is there any other way to retrieve data from a webservice then ?



Hello Friends,
Myself Prashant.

Me giving u WebService Example for Android.

Part - 1:
In this part I giving small demo for webservice running in Android device.
From this link you can find this example. Where I give Comment for webservice demo.
Please all of you check it.
http://lukencode.com/2010/04/27/calling ... omment-179

Part - 2: Webservice running in Android with database connectivity
Now I am running database connectivity and return value from database and showing in Android device.
Here i m using Microsoft SQL connectivity. You can use your way.
For that u have to download this file
SQL connectivity jar file for webservice:
http://www.4shared.com/file/IxoPooiE/sqljdbc.html
Ksoap Library File for android project.
http://www.4shared.com/file/uOhx5aoj/ks ... 4-jar.html

This is good example for you all.

First We create Dynamic Project usign Eclipse
Add this package and class.
Package Name: org.webservice.pa
Class Name : GetDatabaseRecords.java
and also create once class for bean.(Setter-Getter Property).
Class Name : BookData.java


BookData.java

package org.webservice.pa;

public class BookData
{

public String bookCode;
public String bookName;
public String authorName;

public String getBookCode() {
return bookCode;
}
public void setBookCode(String bookCode) {
this.bookCode = bookCode;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public String getAuthorName() {
return authorName;
}
public void setAuthorName(String authorName) {
this.authorName = authorName;
}

}


GetDatabaseRecords.java

package org.webservice.pa;

public class GetDatabaseRecords
{

public BookData[] getBookDetails{
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
ArrayList<BookData> bookDataList = new ArrayList<BookData>();
BookData bookData = null;
try
{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");//Driver Name
con = DriverManager.getConnection("connectionUrl");//connection URL
stmt = con.createStatement();
rs = stmt.executeQuery("select * from BookDetails");//Table Name
while (rs.next())
{
bookData= new BookData();
bookData.setBookCode(rs.getString("bookCode"));
bookData.setBookName(rs.getString("bookName"));
bookData.setAuthorName(rs.getString("authorName"));
bookDataList.add(bookData);
}
}catch (Exception e)
{
e.printStackTrace();
}
finally {
try {
rs.close();
} catch(Exception e) {}
try {
stmn.close();
} catch(Exception e) {}
try {
con.close();
} catch(Exception e) {}
}
return (BookData[])bookDataList.toArray(new BookData[bookDataList.size()]);
}
}

Now Right click on GetDatabaseRecords.java file and select "WebService" option.
Now further step is same as posted my Part 1:
Click finish.
and test your service it will return BookData object.
Here our Dynamic WebProject task is completed.


Now you want to create Android Project for calling above WebService.
Now u add "ksoap" library File in android project:
Download from here:
http://www.4shared.com/file/uOhx5aoj/ks ... 4-jar.html

public class MainActivity extends Activity {
private String METHOD_NAME = "getBookDetails"; // our webservice method name
private String NAMESPACE = "http://pa.webservice.org"; // Here package name in webservice with reverse order.
private String SOAP_ACTION = NAMESPACE + METHOD_NAME; // NAMESPACE + method name
private static final String URL = "http://192.168.1.1:8080/WebServiceDemo/services/GetDatabaseRecords?wsdl"; // you must use ipaddress here, don't use Hostname or localhost

public void onCreate(Bundle icicle)
{
super.onCreate(icicle);
setContentView(R.layout.main);
TextView tv = (TextView) findViewById(R.id.txtsearch);
try
{
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
androidHttpTransport.call(SOAP_ACTION,envelope);
SoapObect so = (SoapObject)envelope.bodyIn;

System.out.println("Counter: "+so.getPropertyCount());

for(int i =0; i < so.getPropertyCount(); i++){
SoapObject soap = (SoapObject) so.getProperty(i);
System.out.println("BookCode :: "+ soap.getProperty("bookCode"));
System.out.println("BookName :: "+ soap.getProperty("bookName"));
System.out.println("AuthorName :: "+ soap.getProperty("authorName"));
}

tv.setText(so.toString());
} catch (Exception E) {
E.printStackTrace();
tv.setText("ERROR:" + E.getClass().getName() + ": " + E.getMessage());
}
}
}


Now you can run your project and it's work fine
:)

And if you have any doubt just tell me.


Thanks & Regards,
Prashant Adesara.
PrashantAdesara
Freshman
Freshman
 
Posts: 6
Joined: Sat Aug 28, 2010 7:24 am

Re:

Postby PrashantAdesara » Sat Aug 28, 2010 7:59 am

Cybermat wrote:Hi Lex, not sure if you were able to solve your problem, but I ran into the same issue and I was able to solve it using the following method. I hope it solves your issue. If not, let me know and post your SOAP return in XML format. So that it would be easier for us to troubleshoot.

HttpTransport androidHttpTransport = new HttpTransport(URL);
try
{
androidHttpTransport.call(SOAP_ACTION, envelope);
SoapObject resultsRequestSOAP = (SoapObject) envelope.bodyIn;
Vector XXXX = (Vector) resultsRequestSOAP.getProperty("[Data element name]");


Just treat the Vector as a normal Java vector, then you should be able to pull all your data
element out


}
catch (Exception aE)
{
aE.printStackTrace ();;
}
}



Hello Cybermat.
Myself Prashant.

Me giving u WebService Example for Android.

Part - 1:
In this part I giving small demo for webservice running in Android device.
From this link you can find this example. Where I give Comment for webservice demo.
Please all of you check it.
http://lukencode.com/2010/04/27/calling ... omment-179

Part - 2: Webservice running in Android with database connectivity
Now I am running database connectivity and return value from database and showing in Android device.
Here i m using Microsoft SQL connectivity. You can use your way.
For that u have to download this file
SQL connectivity jar file for webservice:
http://www.4shared.com/file/IxoPooiE/sqljdbc.html
Ksoap Library File for android project.
http://www.4shared.com/file/uOhx5aoj/ks ... 4-jar.html

This is good example for you all.

First We create Dynamic Project usign Eclipse
Add this package and class.
Package Name: org.webservice.pa
Class Name : GetDatabaseRecords.java
and also create once class for bean.(Setter-Getter Property).
Class Name : BookData.java


BookData.java

package org.webservice.pa;

public class BookData
{

public String bookCode;
public String bookName;
public String authorName;

public String getBookCode() {
return bookCode;
}
public void setBookCode(String bookCode) {
this.bookCode = bookCode;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public String getAuthorName() {
return authorName;
}
public void setAuthorName(String authorName) {
this.authorName = authorName;
}

}


GetDatabaseRecords.java

package org.webservice.pa;

public class GetDatabaseRecords
{

public BookData[] getBookDetails{
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
ArrayList<BookData> bookDataList = new ArrayList<BookData>();
BookData bookData = null;
try
{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");//Driver Name
con = DriverManager.getConnection("connectionUrl");//connection URL
stmt = con.createStatement();
rs = stmt.executeQuery("select * from BookDetails");//Table Name
while (rs.next())
{
bookData= new BookData();
bookData.setBookCode(rs.getString("bookCode"));
bookData.setBookName(rs.getString("bookName"));
bookData.setAuthorName(rs.getString("authorName"));
bookDataList.add(bookData);
}
}catch (Exception e)
{
e.printStackTrace();
}
finally {
try {
rs.close();
} catch(Exception e) {}
try {
stmn.close();
} catch(Exception e) {}
try {
con.close();
} catch(Exception e) {}
}
return (BookData[])bookDataList.toArray(new BookData[bookDataList.size()]);
}
}

Now Right click on GetDatabaseRecords.java file and select "WebService" option.
Now further step is same as posted my Part 1:
Click finish.
and test your service it will return BookData object.
Here our Dynamic WebProject task is completed.


Now you want to create Android Project for calling above WebService.
Now u add "ksoap" library File in android project:
Download from here:
http://www.4shared.com/file/uOhx5aoj/ks ... 4-jar.html

public class MainActivity extends Activity {
private String METHOD_NAME = "getBookDetails"; // our webservice method name
private String NAMESPACE = "http://pa.webservice.org"; // Here package name in webservice with reverse order.
private String SOAP_ACTION = NAMESPACE + METHOD_NAME; // NAMESPACE + method name
private static final String URL = "http://192.168.1.1:8080/WebServiceDemo/services/GetDatabaseRecords?wsdl"; // you must use ipaddress here, don't use Hostname or localhost

public void onCreate(Bundle icicle)
{
super.onCreate(icicle);
setContentView(R.layout.main);
TextView tv = (TextView) findViewById(R.id.txtsearch);
try
{
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
androidHttpTransport.call(SOAP_ACTION,envelope);
SoapObect so = (SoapObject)envelope.bodyIn;

System.out.println("Counter: "+so.getPropertyCount());

for(int i =0; i < so.getPropertyCount(); i++){
SoapObject soap = (SoapObject) so.getProperty(i);
System.out.println("BookCode :: "+ soap.getProperty("bookCode"));
System.out.println("BookName :: "+ soap.getProperty("bookName"));
System.out.println("AuthorName :: "+ soap.getProperty("authorName"));
}

tv.setText(so.toString());
} catch (Exception E) {
E.printStackTrace();
tv.setText("ERROR:" + E.getClass().getName() + ": " + E.getMessage());
}
}
}


Now you can run your project and it's work fine
:)

And if you have any doubt just tell me.


Thanks & Regards,
Prashant Adesara.
PrashantAdesara
Freshman
Freshman
 
Posts: 6
Joined: Sat Aug 28, 2010 7:24 am

Re:

Postby PrashantAdesara » Sat Aug 28, 2010 8:01 am

netmercury wrote:I have the same problem as well!!!!

I have set up the webservice with java and deployed into tomcat.
I am using ksoap2 as webservice client in my app.

Couldn't cast the develope.getResponse() into any type....
Anyone has solution?

Thank you.


Hello netMurcury
Myself Prashant.

Me giving u WebService Example for Android.

Part - 1:
In this part I giving small demo for webservice running in Android device.
From this link you can find this example. Where I give Comment for webservice demo.
Please all of you check it.
http://lukencode.com/2010/04/27/calling ... omment-179

Part - 2: Webservice running in Android with database connectivity
Now I am running database connectivity and return value from database and showing in Android device.
Here i m using Microsoft SQL connectivity. You can use your way.
For that u have to download this file
SQL connectivity jar file for webservice:
http://www.4shared.com/file/IxoPooiE/sqljdbc.html
Ksoap Library File for android project.
http://www.4shared.com/file/uOhx5aoj/ks ... 4-jar.html

This is good example for you all.

First We create Dynamic Project usign Eclipse
Add this package and class.
Package Name: org.webservice.pa
Class Name : GetDatabaseRecords.java
and also create once class for bean.(Setter-Getter Property).
Class Name : BookData.java


BookData.java

package org.webservice.pa;

public class BookData {
public String bookCode;
public String bookName;
public String authorName;

public String getBookCode() {
return bookCode;
}
public void setBookCode(String bookCode) {
this.bookCode = bookCode;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public String getAuthorName() {
return authorName;
}
public void setAuthorName(String authorName) {
this.authorName = authorName;
}

}


GetDatabaseRecords.java

package org.webservice.pa;
public class GetDatabaseRecords{

public BookData[] getBookDetails{
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
ArrayList<BookData> bookDataList = new ArrayList<BookData>();
BookData bookData = null;
try
{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");//Driver Name
con = DriverManager.getConnection("connectionUrl");//connection URL
stmt = con.createStatement();
rs = stmt.executeQuery("select * from BookDetails");//Table Name
while (rs.next())
{
bookData= new BookData();
bookData.setBookCode(rs.getString("bookCode"));
bookData.setBookName(rs.getString("bookName"));
bookData.setAuthorName(rs.getString("authorName"));
bookDataList.add(bookData);
}
}catch (Exception e)
{
e.printStackTrace();
}
finally {
try {
rs.close();
} catch(Exception e) {}
try {
stmn.close();
} catch(Exception e) {}
try {
con.close();
} catch(Exception e) {}
}
return (BookData[])bookDataList.toArray(new BookData[bookDataList.size()]);
}
}

Now Right click on GetDatabaseRecords.java file and select "WebService" option.
Now further step is same as posted my Part 1:
Click finish.
and test your service it will return BookData object.
Here our Dynamic WebProject task is completed.


Now you want to create Android Project for calling above WebService.
Now u add "ksoap" library File in android project:
Download from here:
http://www.4shared.com/file/uOhx5aoj/ks ... 4-jar.html

public class MainActivity extends Activity {
private String METHOD_NAME = "getBookDetails"; // our webservice method name
private String NAMESPACE = "http://pa.webservice.org"; // Here package name in webservice with reverse order.
private String SOAP_ACTION = NAMESPACE + METHOD_NAME; // NAMESPACE + method name
private static final String URL = "http://192.168.1.1:8080/WebServiceDemo/services/GetDatabaseRecords?wsdl"; // you must use ipaddress here, don't use Hostname or localhost

public void onCreate(Bundle icicle)
{
super.onCreate(icicle);
setContentView(R.layout.main);
TextView tv = (TextView) findViewById(R.id.txtsearch);
try
{
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
androidHttpTransport.call(SOAP_ACTION,envelope);
SoapObect so = (SoapObject)envelope.bodyIn;

System.out.println("Counter: "+so.getPropertyCount());

for(int i =0; i < so.getPropertyCount(); i++){
SoapObject soap = (SoapObject) so.getProperty(i);
System.out.println("BookCode :: "+ soap.getProperty("bookCode"));
System.out.println("BookName :: "+ soap.getProperty("bookName"));
System.out.println("AuthorName :: "+ soap.getProperty("authorName"));
}

tv.setText(so.toString());
} catch (Exception E) {
E.printStackTrace();
tv.setText("ERROR:" + E.getClass().getName() + ": " + E.getMessage());
}
}
}


Now you can run your project and it's work fine
:)

And if you have any doubt just tell me.


Thanks & Regards,
Prashant Adesara.
PrashantAdesara
Freshman
Freshman
 
Posts: 6
Joined: Sat Aug 28, 2010 7:24 am

Re: Calling a web service from Android

Postby DoM » Wed Sep 01, 2010 8:59 am

Hi everyone,is possible to configure tcp monitor in eclipse,to see the request and response in xml format?How can i do it?
DoM
Freshman
Freshman
 
Posts: 9
Joined: Mon Mar 16, 2009 12:43 pm

Top
PreviousNext

Return to Other Coding-Problems

Who is online

Users browsing this forum: No registered users and 17 guests