BlackBerry Forums Support Community

BlackBerry Forums Support Community (http://www.blackberryforums.com/)
-   Developer Forum (http://www.blackberryforums.com/developer-forum/)
-   -   Help needed in processing a web service response (http://www.blackberryforums.com/developer-forum/192862-help-needed-processing-web-service-response.html)

karthik25 06-07-2009 11:48 PM

Help needed in processing a web service response
 
Hi,

I am a beginner in BlackBerry development. I am trying to call a web service and process the response. I am successfully able to call the web service but I have trouble parsing the response. Can you please help me in deciphering what I am missing? It would do a world of good to me! Thanks in advance!!

Here is the code i am using.

Code:

import net.rim.device.api.ui.UiApplication;

public class MobileEdu extends UiApplication {
        public static void main(String[] args) {
                MobileEdu theApp = new MobileEdu();
                theApp.enterEventDispatcher();
        }
       
        public MobileEdu() {
                pushScreen(new TestScreen());
        }
}


Code:

import java.util.Vector;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransport;
import org.kxml2.kdom.Element;

import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.component.SeparatorField;
import net.rim.device.api.ui.container.MainScreen;

public class TestScreen extends MainScreen implements FieldChangeListener {
        PictureBackgroundButtonField _pButton;
        LabelField lblInfo;

        public TestScreen(){
                _pButton = new PictureBackgroundButtonField("study",Field.FOCUSABLE,"study.png");
        _pButton.setChangeListener(this);
                add(_pButton);
               
                add(new SeparatorField());
               
                lblInfo = new LabelField("");
                add(lblInfo);
        }
       
    public void fieldChanged(Field field, int context)
    {

        String text = "";
       
        if (field instanceof PictureBackgroundButtonField) {
            text = ((PictureBackgroundButtonField)field).getText();
        }
       
        Dialog.inform(text + " was clicked.");
       
        String serviceUrl = "";
            String serviceNamespace = "";
            String soapAction = "";
            String soapMethod = "GetWeatherByZipCode";

                String result = "";

                SoapObject rpc = new SoapObject(serviceNamespace, soapMethod);
                rpc.addProperty("ZipCode", "75080");

                SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);

                envelope.bodyOut = rpc;
                envelope.dotNet = true;
                envelope.encodingStyle = SoapSerializationEnvelope.XSD;

                HttpTransport ht = new HttpTransport(serviceUrl);
                ht.debug = true;

                try
                {
                        ht.call(soapAction, envelope);
                        //result = (envelope.getResult()).toString();
                       
                        SoapObject body = (SoapObject)envelope.bodyIn;
                       
                        Vector wtList = (Vector)body.getProperty("Details");                       
                        result = Integer.toString(wtList.size());
                }
                catch(org.xmlpull.v1.XmlPullParserException ex2){
                        result = "1 - " + ex2.toString();
                }
                catch(Exception ex){
                        result = "2 - " + ex.toString();
                }
               
                lblInfo.setText(result);
    }
}

Web service's response:

Code:

  <?xml version="1.0" encoding="utf-8" ?>
- <WeatherForecasts xmlns:xsi="" xmlns:xsd="" xmlns="">
  <Latitude>32.9659843</Latitude>
  <Longitude>96.74525</Longitude>
  <AllocationFactor>0.002192</AllocationFactor>
  <FipsCode>48</FipsCode>
  <PlaceName>RICHARDSON</PlaceName>
  <StateCode>TX</StateCode>
- <Details>
- <WeatherData>
  <Day>Sunday, June 07, 2009</Day>
  <WeatherImage>url</WeatherImage>
  <MaxTemperatureF>94</MaxTemperatureF>
  <MinTemperatureF>74</MinTemperatureF>
  <MaxTemperatureC>34</MaxTemperatureC>
  <MinTemperatureC>23</MinTemperatureC>
  </WeatherData>
- <WeatherData>
  <Day>Monday, June 08, 2009</Day>
  <WeatherImage>url</WeatherImage>
  <MaxTemperatureF>94</MaxTemperatureF>
  <MinTemperatureF>74</MinTemperatureF>
  <MaxTemperatureC>34</MaxTemperatureC>
  <MinTemperatureC>23</MinTemperatureC>
  </WeatherData>
- <WeatherData>
  <Day>Tuesday, June 09, 2009</Day>
  <WeatherImage>url</WeatherImage>
  <MaxTemperatureF>95</MaxTemperatureF>
  <MinTemperatureF>76</MinTemperatureF>
  <MaxTemperatureC>35</MaxTemperatureC>
  <MinTemperatureC>24</MinTemperatureC>
  </WeatherData>
- <WeatherData>
  <Day>Wednesday, June 10, 2009</Day>
  <WeatherImage>url</WeatherImage>
  <MaxTemperatureF>93</MaxTemperatureF>
  <MinTemperatureF>74</MinTemperatureF>
  <MaxTemperatureC>34</MaxTemperatureC>
  <MinTemperatureC>23</MinTemperatureC>
  </WeatherData>
- <WeatherData>
  <Day>Thursday, June 11, 2009</Day>
  <WeatherImage>url</WeatherImage>
  <MaxTemperatureF>93</MaxTemperatureF>
  <MinTemperatureF>73</MinTemperatureF>
  <MaxTemperatureC>34</MaxTemperatureC>
  <MinTemperatureC>23</MinTemperatureC>
  </WeatherData>
- <WeatherData>
  <Day>Friday, June 12, 2009</Day>
  <WeatherImage>url</WeatherImage>
  <MaxTemperatureF>93</MaxTemperatureF>
  <MinTemperatureF>73</MinTemperatureF>
  <MaxTemperatureC>34</MaxTemperatureC>
  <MinTemperatureC>23</MinTemperatureC>
  </WeatherData>
- <WeatherData>
  <Day>Saturday, June 13, 2009</Day>
  <WeatherImage>url</WeatherImage>
  <MaxTemperatureF>94</MaxTemperatureF>
  <MinTemperatureF>73</MinTemperatureF>
  <MaxTemperatureC>34</MaxTemperatureC>
  <MinTemperatureC>23</MinTemperatureC>
  </WeatherData>
  </Details>
  </WeatherForecasts>

Sorry, I had to remove the links, as I am not able to post them..

I can successfully use the getResult().toString() method to get the result and just display it. But I need to parse it as xml for processing complex return types as above. I appreciate any help as I have been breaking my head in this...

Thanks in advance

Regards,
Karthik

Dougsg38p 06-08-2009 12:13 AM

You can use the DOM API or the SAX Parser.

For DOM, check the API docs for Document and DocumentBuilder.

For SAX, check the API docs for SAXParser and related classes.

There is also an example in the sample code that ships with the JDE.

karthik25 06-08-2009 01:37 AM

Hi Doug,

Thanks a lot for your response.

I totally forgot the option of using DOM / SAX. I used the following code to parse the XML response. But I get a class cast exception. Can you please check and let me know what is wrong with this.
I would love to experiment and find it out, but the problem is that the simulator takes a lot of time to start in my machine and so it would be
great if you could help me out. I cannot figure out what I am missing.

Code:

ht.call(soapAction, envelope);

DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();                       
DocumentBuilder db=dbf.newDocumentBuilder();

//I guess this part is wrong probably -- I am sure that the remaining code works
InputStream iStr =  (InputStream)envelope.getResponse();

Document dom = db.parse(iStr);

org.w3c.dom.Element docFile = dom.getDocumentElement();
docFile.normalize();

org.w3c.dom.NodeList nl_name = docFile.getElementsByTagName("PlaceName");
org.w3c.dom.Element nl_name_elem = (org.w3c.dom.Element) nl_name.item(0);
String nl_name_value = nl_name_elem.getFirstChild().getNodeValue();
result = nl_name_value;

Thanks again for responding!

Edit:

Given below is the exception I get and the string that follows after "[" is the output received by using envelope.getResponse().toString() -- truncated

java.lang.ClassCastException

[ anyType{Latiture=32.9659843;Longitude=96.74525;All ocationFactor=0.002192;FipsCode=48;PlaceName=Richa rdson;StateCode=TX;Details=anyType{WeatherData=any Type{Day=....

Regards,
Karthik

karthik25 06-08-2009 09:15 PM

Can somebody help me with this?

Dougsg38p 06-08-2009 11:25 PM

There isn't enough info here.

How was envelope declared? What line of code causes the exception?

karthik25 06-09-2009 12:47 AM

Hi Doug,

Thanks for your reply again. I have pasted the entire code and the exception i get is a class cast exception (java.lang.ClassCastException) whenever I am trying to parse the response using getResponse() method of the envelope as given below. I really don't know what I am missing. I have tried various means, but i have just hit a dead end. I tried to find some samples online but all of those examples receives the response, prints it using toString() and that's it! Is it uncommon to use web service calls in BB? I thought that as it doesn't have a good database support, most of BB applications will be using web services extensively.

P.S - I have removed the links as BB Forums doesn't allow me to post the links
Also the XML responses I receive are given above.

Code:

package com.rim.core.mobileedu;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Vector;

import javax.xml.parsers.SAXParser;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransport;
import org.ksoap2.*;
import org.kxml2.kdom.Element;
import org.w3c.dom.*;
import org.xml.sax.helpers.DefaultHandler;
import org.xmlpull.v1.XmlPullParser;

import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.component.SeparatorField;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.xml.jaxp.XMLParser;
import net.rim.device.api.xml.parsers.DocumentBuilder;
import net.rim.device.api.xml.parsers.DocumentBuilderFactory;

import net.rim.device.api.xml.parsers.*;
 
public class TestScreen extends MainScreen implements FieldChangeListener {
        PictureBackgroundButtonField _pButton;
        LabelField lblInfo;

        public TestScreen(){
                _pButton = new PictureBackgroundButtonField("study",Field.FOCUSABLE,"study.png");
        _pButton.setChangeListener(this);
                add(_pButton);
               
                add(new SeparatorField());
               
                lblInfo = new LabelField("");
                add(lblInfo);
        }
       
    public void fieldChanged(Field field, int context)
    {

        String text = "";
       
        if (field instanceof PictureBackgroundButtonField) {
            text = ((PictureBackgroundButtonField)field).getText();
        }
       
        Dialog.inform(text + " was clicked.");
       
        String serviceUrl = "";
            String serviceNamespace = "";
            String soapAction = "GetWeatherByZipCode";
            String soapMethod = "GetWeatherByZipCode";

        String result = "";

        SoapObject rpc = new SoapObject(serviceNamespace, soapMethod);
        rpc.addProperty("ZipCode", "75080");

        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);

        envelope.bodyOut = rpc;
        envelope.dotNet = true;
        envelope.encodingStyle = SoapSerializationEnvelope.XSD;

        HttpTransport ht = new HttpTransport(serviceUrl);
        ht.debug = true;

        String results_temp = "";
       
        try
        {
                ht.call(soapAction, envelope);
               
                SoapObject body = (SoapObject)envelope.getResponse();
               
                results_temp = (envelope.getResult()).toString();
               
                DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();                       
                DocumentBuilder db=dbf.newDocumentBuilder();
                InputStream iStr =  (InputStream)envelope.bodyIn;
                Document dom = db.parse(iStr);
               
                org.w3c.dom.Element docFile = dom.getDocumentElement();
                docFile.normalize();
               
                org.w3c.dom.NodeList nl_name = docFile.getElementsByTagName("PlaceName");
                org.w3c.dom.Element nl_name_elem = (org.w3c.dom.Element) nl_name.item(0);
                String nl_name_value = nl_name_elem.getFirstChild().getNodeValue();
                result = nl_name_value;
        }
        catch(org.xmlpull.v1.XmlPullParserException ex2){
                ex2.printStackTrace();
        }
        catch(Exception ex){
                ex.printStackTrace();                       
        }
       
        lblInfo.setText(result);
    }
}

Please help me resolve this problem, as it would do a world of good.

Thanks,
Karthik

koic 06-14-2009 07:18 PM

Quote:

Originally Posted by karthik25 (Post 1402066)
...BB Forums doesn't allow me to post the links.

You can, but make them look a little bit diffeternt ;-)
Example:
//na.blackberry.com/eng/developers/javaappdev/javadevenv.jsp
P.S. 'http' first, of course.

koic 06-22-2009 10:08 AM

Ok,
one more thing I've just discovered.
Try
PHP Code:

SoapObject body = (SoapObject)envelope.bodyIn

instead of
PHP Code:

SoapObject body = (SoapObject)envelope.getResponse(); 

Somehow first line does not throw ClassCastException,
whereas second one does !? :shock:

bemshaswing 06-22-2009 11:05 AM

koic, you might want to try to find out what the class of the 2nd object is, so

System.out.println(envelope.getResponse().getClass ().getName());

koic 06-22-2009 01:06 PM

Thanks bemshaswing, that was the problem:
envelope.getResponse() sometimes returns org.ksoap2.serialization.SoapPrimitive
which cannot be cast to org.ksoap2.serialization.SoapObject, -
they are on parallel branches :-o
But bodyIn is org.ksoap2.serialization.SoapObject:idea:
So does this solve the ClassCastException issue ?
I'm afraid not, have to figure out what to do whith that SoapObject resurrected from bodyIn....

karthik25 06-23-2009 05:58 PM

@bemshaswing and koic

I was fed up with this method and chose to use another method to process the xml response and that's working.

I will soon post the link that has a very good tutorial regarding this (I don't have the link stored in the m/c i am using right now)

koic 06-23-2009 06:36 PM

Well, the strange thing is that ksoap2 works only one way - serializes and sends soap to service.
The problems come with response, - needs to be de-serialized.
Recently I 'moved' to SAX parser, - works fine (y)


All times are GMT -5. The time now is 08:57 PM.

Powered by vBulletin® Version 3.6.12
Copyright ©2000 - 2014, Jelsoft Enterprises Ltd.