How to parse a SoapObject in android - android

I'm using webservices for an application to get the data from external servers. I'm able to connect to the server, send my SOAP request and able get the data back to my android class as SoapObject.
Here I'm having trouble parsing this SoapObject to retrieve the values (as strings) coming from the webservice.
My code is here:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list);
mInflater = (LayoutInflater)getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
System.out.println("Entered "+getClass().getSimpleName());
//Calling the web service to get the documents list
callService("getDocumentsList","http://wservice.friedmaggy.com/getDocumentsList");
-- I have created callService method to call the webservice.:
public void callService(String operation, String soapaction)
{
try {
String SOAP_ACTION = soapaction;
String OPERATION_NAME = operation;
String WSDL_TARGET_NAMESPACE = getString(R.string.targetNamespace);
String SOAP_ADDRESS = getString(R.string.soapAddress);
SoapObject request = new SoapObject(
WSDL_TARGET_NAMESPACE, OPERATION_NAME);
System.out.println("SOAP_ACTION "+SOAP_ACTION);
System.out.println("OPERATION_NAME "+OPERATION_NAME);
System.out.println("WSDL_TARGET_NAMESPACE "+WSDL_TARGET_NAMESPACE);
System.out.println("SOAP_ADDRESS "+SOAP_ADDRESS);
// System.out.println("SOAP_ACTION "+SOAP_ACTION);
PropertyInfo propInfo = new PropertyInfo();
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
HttpTransportSE httpTransport = new HttpTransportSE(
SOAP_ADDRESS);
envelope.setOutputSoapObject(request);
httpTransport.call(SOAP_ACTION, envelope);
SoapObject response = (SoapObject) envelope.bodyIn;
if(response.getPropertyCount()>0){
data=new StringBuilder();
for (int i = 0; i < response.getPropertyCount(); i++) {
Course c = new Course((SoapObject) response.getProperty(i));
courseList.add(c);
}
for (Course c : courseList) {
data.append("CourseName :" + c.getName());
results.add(c.getName());
}
-- As seen above, i'm passing the whole response object to another bean class to fetch the values.(Course c = new Course((SoapObject) response.getProperty(i));)
Can you help me how to parse this response object to fetch the required String values out.?

androidHttpTransport.call(SOAP_ACTION, envelope);
Object response = envelope.getResponse();
Vector<SoapObject> res= null;
if (response instanceof SoapObject) {
res = new Vector();
res.add((SoapObject) response);
} else if (response instanceof Vector) {
res = (Vector<SoapObject>) response;
}
for(SoapObject so1: res){
//retrieve String here from soap object using this
so1.getProperty(0).toString();
//then so1.getProperty(1).toString and likewise
}

Related

how to display a datable from webservice using SOAP in a spinner oF Android

I am still new in this.
I connected my android app to SQL Server using a web-service written in Asp.net (visual studio).
I used SOAP, I want to access the datable written in the web-service and put it in a spinner.
This is my code in Visual Studio (web service)
//get product from inventory
[WebMethod]
public DataTable getProduct()
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = ConfigurationManager.ConnectionStrings["WebConnectionString"].ToString();
conn.Open();
SqlCommand cmd = new SqlCommand("Select SmallDescription from [Product]", conn);
SqlDataReader reader = cmd.ExecuteReader();
DataTable dt = new DataTable("getproduct");
dt.Load(reader);
conn.Close();
return dt;
}
And this is my java code:
Thread nt = new Thread() {
#Override
public void run() {
// method getproduct
SoapObject request = new SoapObject(NAMESPACE,
METHOD_NAME);
final SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
// result.getPropertyInfo(result, pi);
/**************** HTTP Post ******************/
HttpTransportSE androidHttpTransport = new HttpTransportSE(
URL);
try {
androidHttpTransport.call(
warehouselist_SOAP_ACTION, envelope);
} catch (Exception e) {
e.printStackTrace();
Log.d("Not working", e.toString());
// Toast.makeText(getApplicationContext(),
// "Not working", Toast.LENGTH_LONG).show();
}
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(MainActivity.this, "hola",
Toast.LENGTH_SHORT).show();
TextView e = (TextView) findViewById(R.id.textView5);
SoapObject resultRequestSOAP = (SoapObject) envelope.bodyIn;
SoapObject nameResult = (SoapObject) resultRequestSOAP
.getProperty(0);
int count = nameResult.getPropertyCount();
//e.setText(Integer.toString(count));
StringBuilder stringBuilder = new
StringBuilder();
/*
* Retrieve one property from the complex
* SoapObject response
*/
for (int i = 0; i < count - 1; i++) {
SoapObject simpleSuggestion = (SoapObject)
nameResult.getProperty(i);
stringBuilder.append(simpleSuggestion.getProperty(
"Small Description").toString());
stringBuilder.append("\n");
}
String temp = stringBuilder.toString();
// MY QUEST IS HERE HOW TO DISPLAY IT IN A SPINNER!!!!!!
}
});
}
};
nt.start();
}
});
}
}
thanks !
First of all you need to parse your database response and stored into array list or in array whatever you like,if response is in Json format then you can use JsonArray or JsonObject to parse your response or if response in xml then you can use DOM or SAX parser as u like, after you have to create one spinner adapter e.g. here, pass your array list or array to the adapter and set as whatever your requirement ,and for more help here is the best example for loading database response into a spinner.

getting string list from a web service in android app

I have a web service made in asp.net which returns a list of String .
here is the code :
<WebMethod()> Public Function HelloWorld() As List(Of String)
Dim a As New List(Of String)
a.Add("2")
a.Add("2")
a.Add("2")
a.Add("2")
a.Add("2")
Return a
End Function
and this is the coding in android app :
SoapObject request = new SoapObject(wsdl_target_namespace,operation_name);
SoapSerializationEnvelope envelope= new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
HttpTransportSE httpTransport = new HttpTransportSE(soap_address);
Log.d("test", "test");
try{
httpTransport.call(SOAP_ACTION, envelope);
Object response = envelope.getResponse();
txt.setText(String.valueOf(response));
Log.d("test", String.valueOf(response));
} catch(Exception exception){
txt.setText(exception.toString());
Log.d("error_mine", exception.toString());
}
this code returns me this in text box :
anyType {
string=2;
string=2;
string=2;
string=2;
string=2
}
but i want this as a list to populate a list view .
how can i do this ?
Try Following code :
// ArrayList to store the data from web service :
// **You can initialize this string globally**
ArrayList<String> mArrayList = new ArrayList<String>();
-----------------------------------------------
Object response = envelope.getResponse();
// need to replace this line with the following
-----------------------------------------------
// Get the SoapResult from the envelope body.
SoapObject result = (SoapObject) envelope.bodyIn;
if (result != null) {
for (int i = 0; i < result.getPropertyCount(); i++) {
mArrayList.add(result.getProperty(i));
}
}

how to parse through complex soap objects in Android

Hello Friends i am using soap web services very first time in my code.
but i am not getting how to handle nested soap objects.
this is my code
private final String URL = "http://192.168.0.20/BookingEngineService/HotelBookingService.asmx";
private final String SOAP_ACTION = "http://tempuri.org/AndroidTestRequest";
private final String METHOD_NAME = "AndroidTestRequest";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("User", "abcd#xyz.com");
request.addProperty("Password", "abcd#123");
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.headerOut = new Element[1];
envelope.headerOut[0] = buildAuthHeader();
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try {
androidHttpTransport.call(SOAP_ACTION, envelope);
Log.i("myAppEnvelope", envelope.toString());
SoapObject response = (SoapObject) envelope.getResponse();
// here i am trying to get values from response which is soap object
for (int i = 0; i < response.getPropertyCount(); i++) {
SoapObject con = (SoapObject) response.getProperty(i);
Log.e("Continent", con.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
i am getting soap object as a response and which is very complex so i am not getting how to parse it. this is my response this is very small part of my response.
I am not getting how to get values from SoapObject -> Properties -> elementData -> value-> property -> elementData and so on ... its too complex please help me.
You can convert soap object to a string. Check the example code bellow
Eg:
final SoapPrimitive response = (SoapPrimitive)envelope.getResponse();
final String str = response.toString();
It's a simple XML parsing. Go through the link for more details.
You can get the response as input stream and convert that into string and using that string, you can create an XML object. Please refer the link for more information.

How to send DateTime to .net webService from android (ksoap2)?

I've a .net webservice, where I have to send a param (type of dateTime), as You can see:
<startDateTime>dateTime</startDateTime>
In Android client, I use ksoap2, and I don't know , How to send that type of data?
Please help with setting this type - code below not works.
PropertyInfo propInfo3 = new PropertyInfo();
propInfo3.name="startDateTime";
propInfo3.value="2012-02-01";
Here is how I call web service methods in my application. Note the method I used to convert java dates. You require an ISO date format.
protected static Object callMethod(String method, Map<String, Object> parameters) throws IOException, XmlPullParserException {
SoapObject request = new SoapObject(WSDL_TARGET_NAMESPACE, method);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.headerOut = new Element[1];
envelope.headerOut[0] = buildAuthHeader();
envelope.setOutputSoapObject(request);
if (parameters != null) {
for (String item : parameters.keySet()) {
Object itemValue = parameters.get(item);
if (itemValue.getClass().getName().equals("java.util.Date")) {
// If it's a date then we have to format it because ksoap
// does not know how to do this.
request.addProperty(item, getSOAPDateString((java.util.Date) itemValue));
} else {
request.addProperty(item, itemValue);
}
}
}
HttpTransportSE httpTransport = new HttpTransportSE(SOAP_ADDRESS, 10000);
httpTransport.debug = true;
httpTransport.call(WSDL_TARGET_NAMESPACE + "/" + method, envelope);
String soapString = httpTransport.requestDump;
System.out.println(soapString);
return envelope.getResponse();
}
Here is the method that returns the actual string:
private static Object getSOAPDateString(java.util.Date itemValue) {
String lFormatTemplate = "yyyy-MM-dd'T'hh:mm:ss'Z'";
DateFormat lDateFormat = new SimpleDateFormat(lFormatTemplate);
String lDate = lDateFormat.format(itemValue);
return lDate;
}
In your server, what's the return from the client?
When I have a problem like this, I show in the Logcat on Android what I'm sending and in the server side what I'm getting.
I had a little problem with date too (I'm using ksoap2 and webservices), I solve my problem sending the date in the util.Date, then I use SimpleDateFormat with a pattern date in my project and convert that string to what I want.
cya,
Bertan
Here is my code that sends to the WS:
public static byte[] send(String... param) throws SocketTimeoutException, IOException, XmlPullParserException, Exception{
//First I send the WS Name
String ws = param[0];
//Second is the operationName
SoapObject soap = new SoapObject(URL_SOAP, param[1]);
Object retorno = null;
int tamParam = param.length;
//The 3 parameter for the infinity its the properties, name and the next it's the value...
if (tamParam > 0) {
for (int i = 2; i < tamParam; i++) {
soap.addProperty(param[i], param[++i]);
}
}
// create a envelope for the soap object
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(soap);
// create a HttpTransport to send the object soap with 15s delay
MyHttpTransport httpTransport = new MyHttpTransport(URL + ws, 15000);
// send the req
Long tempo1 = 0l;
tempo1 = System.currentTimeMillis();
httpTransport.call("", envelope);
retorno = envelope.getResponse();
Long tempo2 = System.currentTimeMillis();
httpTransport.reset();
//I ever get byte[] from the WS...
if (retorno != null) {
byte[] bloc = Base64.decode(retorno.toString(), Base64.DEFAULT);
return bloc;
} else {
return null;
}
}

Passing ArrayList of custom object to kSOAP function

This is the function which is to call the function in the server to perform some task. But i have to pass in a ArrayList and a String value. I have trouble passing the ArrayList to the server. Can anyone tell me what i should do?
public void findLocation(ArrayList<APData> apdatalist, String profilename){
SoapObject request = new SoapObject(NAMESPACE, "FindLocation");
PropertyInfo quotesProperty = new PropertyInfo();
quotesProperty.setName("profileName");
quotesProperty.setValue(profilename);
quotesProperty.setType(String.class);
request.addProperty(quotesProperty);
request.addProperty("AP_List", APData.class);
envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE httpRequest = new HttpTransportSE(URL);
httpRequest.debug = true;
String result = "";
try
{
httpRequest.call(SOAP_ACTION, envelope);
Log.e("Request",httpRequest.requestDump.toString());
SoapPrimitive response = (SoapPrimitive)envelope.getResponse();
Log.e("Response",httpRequest.responseDump.toString());
result = response.toString();
if(result == null){
Log.e("AndroidRuntime", "No location result is return!");
}
}
catch(Exception e)
{
e.printStackTrace();
}
//return temp;
}
I've found a possible solution. I've modified the SoapSerializationEnvelope class to deal with ArrayList.
I modified the method
public void writeObjectBody(XmlSerializer writer, KvmSerializable obj)
public void writeObjectBody(XmlSerializer writer, KvmSerializable obj) throws IOException
{
// Added this code for parsing attributes of KvmSerializable objects
int cnt = obj.getPropertyCount();
PropertyInfo info = new PropertyInfo();
for (int i = 0; i < cnt; i++)
{
Object prop = obj.getProperty(i);
if(!(prop instanceof SoapObject)) {
// prop is a PropertyInfo
obj.getPropertyInfo(i, properties, info);
// Added this code to parse ArrayList objects in requests
if(prop instanceof ArrayList<?>){
ArrayList<?> values = (ArrayList<?>)prop;
for(Object o : values){
writer.startTag(info.namespace, info.name);
writeProperty(writer, o, info);
writer.endTag(info.namespace, info.name);
}
}else if ((info.flags & PropertyInfo.TRANSIENT) == 0)
{
writer.startTag(info.namespace, info.name);
writeProperty(writer, obj.getProperty(i), info);
writer.endTag(info.namespace, info.name);
}
} else {
// prop is a SoapObject
SoapObject nestedSoap = (SoapObject)prop;
writer.startTag(nestedSoap.getNamespace(), nestedSoap.getName());
writeObjectBody(writer, nestedSoap);
writer.endTag(nestedSoap.getNamespace(), nestedSoap.getName());
}
}
}
This seems to work for me

Categories

Resources