how to parse data from Soap envelope object in android - android

SoapObject result = (SoapObject) envelope.getResponse();
SoapObject root = (SoapObject) result.getProperty(0);
SoapObject s_deals = (SoapObject) root.getProperty("InfraWiseDetails");
SoapObject s_deals_1 = (SoapObject) s_deals.getProperty("VisitInfraDetails");
for (int i = 0; i < s_deals_1.getPropertyCount(); i++) {
Object property = s_deals_1.getProperty(i);
if (property instanceof SoapObject) {
SoapObject category_list = (SoapObject) property;
String x = category_list.getProperty("Feedback").toString();
String y = category_list.getProperty("InfraName").toString();
String z = category_list.getProperty("Problem").toString();
}
}
this is my Code
in SoapObject SoapObject result = (SoapObject) envelope.getResponse(); i am getting response --->
anyType{InfraWiseDetails=anyType{VisitInfraDetails=anyType{Feedback=Status OK; InfraName=Tables and Chairs; Problem=null; ResolutionStatus=false; Status=true; };
VisitInfraDetails=anyType{Feedback=Water Quality very poor; InfraName=Water; Problem=Rust in Water; ResolutionStatus=false; Status=false; }; }; VisitMasterId=1; }
I want to Parse data from given SoapObject and get all value of FeedBack, Infraname, Problem... please tell me where am doing wrong i am unable to get value

After long time i am looking on ksoap2 code. Try this :
SoapObject result = (SoapObject) envelope.getResponse();
SoapObject root = (SoapObject) result.getProperty(0);
SoapObject s_deals = (SoapObject) root.getProperty("InfraWiseDetails");
for (int i = 0; i < s_deals.getPropertyCount(); i++) {
SoapObject s_deals_1 = (SoapObject) s_deals.getProperty(i);
String x = s_deals_1.getProperty("Feedback").toString();
String y = s_deals_1.getProperty("InfraName").toString();
String z = s_deals_1.getProperty("Problem").toString();
}

Try like this in your Code , You can parse the data from KSoap
getdata(String SearchValue)- Call this method inside your do inBackground
public void getdata(String SearchValue)
{
// Create request
SoapObject request = new SoapObject(NAMESPACE2, METHOD_NAME2);
PropertyInfo pi4 = new PropertyInfo();
pi4.setName("City");
pi4.setValue(SearchValue);// get the string that is to be sent to the webservice
pi4.setType(String.class);
request.addProperty(pi4);
// Create envelope
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
// Set output SOAP object
envelope.setOutputSoapObject(request);
// Create HTTP call object
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL2);
try {
// Invole web service
androidHttpTransport.call(SOAP_ACTION2, envelope);
// Get the response
SoapPrimitive response = (SoapPrimitive) envelope.getResponse();
//Converting string to Array list
ArrayList<String> Servciecityname_arr= new ArrayList<String>();
if ((response.toString()).contains("{"))
{
SoapObject rep = (SoapObject) envelope.bodyIn;
JSONArray jr = new JSONArray(rep.getPropertyAsString(0));
for (int i = 0; i < jr.length(); i++) {
JSONObject jb = (JSONObject) jr.get(i);
Cityname = jb.getString("CityName123");
Servciecityname_arr.add(Cityname);
}
CITYNAME = new String[Servciecityname_arr.size()];
CITYNAME = Servciecityname_arr.toArray(CITYNAME);
}
else
{
Status_Response = response.toString();
}
} catch (Exception e) {
Log.i(TAG2, "Error in catch");
e.printStackTrace();
}
}

Related

Android Webservice do not return expected data in listview

I want to fetch a listview from webservice in Android app. I managed to get the data when i tried to break my code. But this is what I get when i break the code in the array list:
[com.xxx.example.Hotels#41319dc0, com.xxx.example.Hotels#4131a518, com.xxx.example.Hotels#4132fec8, com.xxx.example.Hotels#413323a0]
Below is my code that called the list.
mainListView = (ListView) findViewById(R.id.lview);
WebService2 cs = new WebService2();
listHt = cs.selectAllHotels();
listAdapter = new HotelArrayAdapter(this, listHt);
mainListView.setAdapter(listAdapter);
Below is the code called the webservice.
public ArrayList<Hotels> selectAllHotels() {
ArrayList<Hotels> lst = new ArrayList<Hotels>();
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
SoapObject table = null;
SoapObject responseBody = null;
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try {
androidHttpTransport.call(SOAP_ACTION, envelope);
responseBody = (SoapObject) envelope.getResponse();
responseBody = (SoapObject) responseBody.getProperty(1);
table = (SoapObject) responseBody.getProperty(0);
for (int i = 0; i < table.getPropertyCount(); i++) {
Hotels dto = new Hotels();
SoapObject row = (SoapObject) table.getProperty(i);
dto.setName(row.getProperty("HOTELNAME").toString());
lst.add(dto);
}
} catch (Exception e) {
e.printStackTrace();
}
return lst;
}

Web Service return null in Android

I have a web service that I use in my android project. One method in my web service return null in android with ksoap2. When I debug the project, envelope is returning like this:
GPSYerBilgisiGetirResponse{GPSYerBilgisiGetirResult=anyType{}; }
Out of android, I run the web service and give parameter to method, returning data like this:
<ArrayOfFirma xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://tempuri.org/">
<Firma>
<gpsilce>BEYOĞLU</gpsilce>
<gpssemt>KASIMPAŞA</gpssemt>
</Firma>
</ArrayOfFirma>
This is my function for using connect to web service
private String[] konumGetir(String ParamPK){
PropertyInfo pk = new PropertyInfo();
pk.name= "pk";
pk.setValue(ParamPK);
pk.type = PropertyInfo.STRING_CLASS;
SoapObject request = new SoapObject(NAMESPACE, "GPSYerBilgisiGetir");
request.addProperty(pk);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.bodyOut=request;
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
androidHttpTransport.debug = true;
try {
androidHttpTransport.call("http://tempuri.org/GPSYerBilgisiGetir", envelope);
SoapObject response = (SoapObject) envelope.getResponse();
konumList=new String[1];
for(int i=0;i<response.getPropertyCount();i++){
Object property = response.getProperty(i);
if(property instanceof SoapObject){
SoapObject firmalar = (SoapObject) property;
konumList[0]=firmalar.getProperty("gpssemt") + "-" + firmalar.getProperty("gpsilce");
}
}
}
catch (Exception e) {
e.printStackTrace();
}
return konumList;
}
This is my web service method:
<WebMethod()> _
Public Function GPSYerBilgisiGetir(ByVal pk As String) As List(Of Firma)
Dim konumlist As New List(Of Firma)
Dim dg As New dgetir("SELECT DISTINCT ILCE,SEMT FROM GPSYERBILGISI WHERE PK='" + pk + "'")
While dg.dtr.Read
Dim gpskonum As New Firma
gpskonum.gpsilce = dg.dtr.Item("ILCE")
gpskonum.gpssemt = dg.dtr.Item("SEMT")
konumlist.Add(gpskonum)
End While
dg.close()
Return konumlist
End Function
Try this code.
private String[] konumGetir(String ParamPK){
SoapObject request = new SoapObject(NAMESPACE, "GPSYerBilgisiGetir");
request.addProperty("pk", ParamPK);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try {
androidHttpTransport.call(SOAP_ACTION_NAME, envelope);
SoapObject result = (SoapObject) envelope.getResponse();
int childCount = result.getPropertyCount();
konumList = new String[childCount];
SoapObject tempArray[] = new SoapObject[childCount];
int i;
for (i = 0; i < childCount; i++) {
tempArray[i] = (SoapObject) result.getProperty(i);
konumList[i] = tempArray.getProperty(0).toString();
}
} catch (Exception e) {
e.printStackTrace();
}
return konumList;
}
Hope it helps.

How to get the result for return statement from JSON parsing?

I've follow the code for parsing the value with JSON from here, but I get the problem in my return statement. I want to put the parsing result into my return statement. How to do that?
Here is my code:
public String MASUK(String user, String password)
{
SoapObject request = new SoapObject(WSDL_TARGET_NAMESPACE,OPERATION_NAME);
PropertyInfo pi = new PropertyInfo();
pi.setName("ccduser");
pi.setValue(user);
pi.setType(String.class);
request.addProperty(pi);
PropertyInfo pi2 = new PropertyInfo();
pi2.setName("password");
pi2.setValue(password);
pi2.setType(String.class);
request.addProperty(pi2);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE httpTransport = new HttpTransportSE(SOAP_ADDRESS);
try
{
httpTransport.call(SOAP_ACTION, envelope);
SoapObject resultSOAP = (SoapObject) envelope.bodyIn;
/* gets our result in JSON String */
String ResultObject = resultSOAP.getProperty(0).toString();
resultSOAP = (SoapObject) envelope.bodyIn;
ResultObject = resultSOAP.getProperty(0).toString();
if (ResultObject.startsWith("{")) { // if JSON string is an object
JSONObj = new JSONObject(ResultObject);
Iterator<String> itr = JSONObj.keys();
while (itr.hasNext()) {
String Key = (String) itr.next();
String Value = JSONObj.getString(Key);
BundleResult.putString(Key, Value);
// System.out.println(bundleResult.getString(Key));
}
}
else if (ResultObject.startsWith("[")) { // if JSON string is an array
JSONArr = new JSONArray(ResultObject);
System.out.println("length" + JSONArr.length());
for (int i = 0; i < JSONArr.length(); i++) {
JSONObj = (JSONObject) JSONArr.get(i);
BundleResult.putString(String.valueOf(i), JSONObj.toString());
// System.out.println(bundleResult.getString(i));
}
}
}
catch (Exception exception)
{
}
return null;
}
If you have JSON array object:
JSONObject jObject = new JSONObject(***JSON String you have ***);
JSONArray contestantObjects = jObject.getJSONArray("*** Array Name ***");
for(int i=0; i<contestantObjects.length(); i++) {
mChannels.setId(contestantObjects.getJSONObject(i).getString("id").toString());
mChannels.setName(contestantObjects.getJSONObject(i).getString("name").toString());
}
If you have just one item:
JSONObject jObject = new JSONObject(***JSON String you have ***);
mPreview.setBody(jObject.getString("*** Item Name ***").toString());
mPreview.setPublishedDate(jObject.getString("publishedDate").toString());
mPreview.setRefKey(jObject.getString("refKey").toString());
mPreview.setTitle(jObject.getString("title").toString());
http://jsonviewer.stack.hu/ is online tool for parsing JSON. its awesome you can use it.
JSONObject prefsJson = new JSONObject(prefsJsonString);
String str = prefsJson.has("str") == true ? prefsJson.getString("str") : "";
Is that ok?
Referring to the link which you have used to parse the JSON String, I would suggest that you return the object bundleResult from your function. Change the return value for your method as public Bundle MASUK(String user, String password).
EDIT
Don't forget to initialize the Bundle object:
private Bundle bundleResult=new Bundle();
And take care not to change the case (upper/lower case) for the variable being used. I could see in your code BundleResult.putString(Key, Value); and the reference link uses bundleResult.putString(Key, Value);

How to parse a SoapObject in 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
}

How can I parse anyType {----} response with ksoap2 [duplicate]

I use a ksoap2 lib for communicating from android client with SOAP web service. Great job was done by ksoap team, but the problem is, there is no any good example how to use it correct in different aspects. For instance I get in soap response following data:
anyType{
StatusSetting=anyType{Id=1; Name=Til afskrivning; LocationId=1; Editable=true; Default=true; Transcribed=false; };
StatusSetting=anyType{Id=2; Name=Afskrevet; LocationId=1; Editable=false; Default=false; Transcribed=true; };
...
}
It's a complex object, or rather a collection of StatusSetting objects.
When I try to get a property of SoapObject it's only 1 property with all that data as a string. It can't be parsed as json too. Unbelievable that nobody met same problem regarding to popularity android is gaining. Would be very cool to know if somebody solved this issue and how.
Thanks.
For example your Response:
anyType
{
FOO_DEALS=anyType
{
CATEGORY_LIST=anyType
{
CATEGORY=Books;
CATEGORY_URL=books_chennai;
CATEGORY_ICON=http://deals.foo.com/common/images/books.png;
CATEGORY_COUNT=1045;
TYPE=1;
SUPERTAG=Books;
};
CATEGORY_LIST=anyType
{
CATEGORY=Cameras;
CATEGORY_URL=cameras_chennai;
CATEGORY_ICON=http://deals.foo.com/common/images/cameras.png;
CATEGORY_COUNT=152;
SUPERTAG=Cameras;
TYPE=1;
};
};
}
For requesting and parsing do like this:
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
// Add the input required by web service
request.addProperty("city","chennai");
request.addProperty("key","10000");
SoapSerializationEnvelope envelope =new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
// Make the soap call.
androidHttpTransport.call(SOAP_ACTION, envelope);
// Get the SoapResult from the envelope body.
resultRequestSOAP = (SoapObject) envelope.bodyIn;
System.out.println("********Response : "+resultRequestSOAP.toString());
SoapObject root = (SoapObject) resultRequestSOAP.getProperty(0);
SoapObject s_deals = (SoapObject) root.getProperty("FOO_DEALS");
StringBuilder stringBuilder = new StringBuilder();
System.out.println("********Count : "+ s_deals.getPropertyCount());
for (int i = 0; i < s_deals.getPropertyCount(); i++)
{
Object property = s_deals.getProperty(i);
if (property instanceof SoapObject)
{
SoapObject category_list = (SoapObject) property;
String CATEGORY = category_list.getProperty("CATEGORY").toString();
String CATEGORY_URL = category_list.getProperty("CATEGORY_URL").toString();
String CATEGORY_ICON = category_list.getProperty("CATEGORY_ICON").toString();
String CATEGORY_COUNT = category_list.getProperty("CATEGORY_COUNT").toString();
String SUPERTAG = category_list.getProperty("SUPERTAG").toString();
String TYPE = category_list.getProperty("TYPE").toString();
stringBuilder.append
(
"Row value of: " +(i+1)+"\n"+
"Category: "+CATEGORY+"\n"+
"Category URL: "+CATEGORY_URL+"\n"+
"Category_Icon: "+CATEGORY_ICON+"\n"+
"Category_Count: "+CATEGORY_COUNT+"\n"+
"SuperTag: "+SUPERTAG+"\n"+
"Type: "+TYPE+"\n"+
"******************************"
);
stringBuilder.append("\n");
}
}
SoapObject countryDetails = (SoapObject)envelope.getResponse();
System.out.println(countryDetails.toString());
ArrayList list = new ArrayList(countryDetails.getPropertyCount());
lv_arr = new String[countryDetails.getPropertyCount()];
for (int i = 0; i < countryDetails.getPropertyCount(); i++) {
Object property = countryDetails.getProperty(i);
if (property instanceof SoapObject) {
SoapObject countryObj = (SoapObject) property;
String countryName = countryObj.getProperty("countryName").toString();
list.add(countryName );
}
}
Hope it should work
Here is a tutorial on how to work with array of complex objects with KSOAP. I found out by countless hours of debugging. Hope this hepls
My Project it's work. Hope this hepls.
SoapObject requestx = new SoapObject(NAMESPACE, METHOD_NAME);
SoapSerializationEnvelope envelopex = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelopex.dotNet = true;
envelopex.setOutputSoapObject(requestx);
HttpTransportSE httpTransportx = new HttpTransportSE(URL);
try {
httpTransportx.call(SOAP_ACTION, envelopex);
SoapObject responsex = (SoapObject)envelopex.getResponse(); // not envelopex.bodyIn;
int i=0;
int RCount=responsex.getPropertyCount();
int[] tbIDArray = new int[RCount+1];
int[] iMonthAarray = new int[RCount+1];
int[] iYearAarray = new int[RCount+1];
String[] sDetailAarray = new String[RCount+1];
for (i = 0; i < RCount; i++) {
Object property = responsex.getProperty(i);
if (property instanceof SoapObject) {
SoapObject info = (SoapObject) property;
String tbID = info.getProperty("tbID").toString();
String iMonth = info.getProperty("iMonth").toString();
String iYear = info.getProperty("iYear").toString();
String sDetail = info.getProperty("sDetail").toString();
tbIDArray[i] =Integer.valueOf(tbID);
iMonthAarray[i] =Integer.valueOf(iMonth);
iYearAarray[i] =Integer.valueOf(iYear);
sDetailAarray[i] =sDetail;
}//if (property instanceof SoapObject) {
}//for (i = 0; i < RCount; i++) {
} catch (Exception exception) {
MsgBox1(exception.toString() , "Error");
}
JSON format is much comfortable. I wrote a simple code to convert SOAP V1 response to JSON:
public static String soapStrToJson(String input)
{
String output;
output = input;
output = output.replace("key=", "\"");
output = output.replace("; value=", "\":");
output = output.replace("; };",",");
output = output.replace("item=anyType{","");
output = output.replace("Map","");
output = output.replace(",}","}");
output = output.replace(", }"," }");
output = output.replace("null","0");
Pattern pattern = Pattern.compile(":(.*?),");
Matcher matcher = pattern.matcher(output);
List<String> wordsToReplace = new ArrayList();
while (matcher.find())
{
String str = matcher.group(0);
if(str.contains("{") || str.contains("["))
continue;
str = str.replace(":", "");
str = str.replace(",", "");
if(str.matches("^-?\\d+$"))
continue;
System.out.println("-->" + str);
wordsToReplace.add(str);
}
for(String str : wordsToReplace)
{
output = output.replace(":"+str+",", ":\""+str+"\",");
}
return output;
}
and used this function as:
parseCategoryJSON( new JSONObject( soapStrToJson( env.getResponse().toString() ) ) )
Note that I am not using env.bodyIn SoapObject.
This may not be the perfect converter for all responses, so modify 'String.replace' and Pattern-Matchers as per your requirement.

Categories

Resources