KXML parsing

Hello,
I'm having difficulty with trying to parse a XML document and none of the examples i could find have this specific querk here's the xml
<?xml version="1.0" encoding="UTF-8" ?>
<webraska>
<status>
<api-version>API 1.4-20021030</api-version>
<message code="200">OK</message>
</status>
<data>
<boundingbox>
<navid latitude="-22.954345" longitude="-43.18376" />
<navid latitude="-22.945374" longitude="-43.174019" />
</boundingbox>
<map href="http://teste.webraska.com.br/gns/ZQZLAJ-1089690201721.png" />
</data>
</webraska>
With my code i can only get up to the 'navid' section before it throws exceptions because the 'navid' tag does not end in '/navid>'
Can anyone provide me with code to get around this? or give sample code on how to process it..
I really only want from this stream the '<map href ' the rest of the xml does not matter but i will also be recieving other xml data where there is even more of this style for me to process..
Thanks in advance
-Snuffy

Hello...
understand that my coding for this has been rather a hack job..
Looking at examples and trying to make things work..
This snippet just calls the other function readmap..
parser.setInput(new InputStreamReader(this._Conn.openInputStream()));
parser.nextTag();
parser.require(XmlPullParser.START_TAG,null,"webraska");
int i =0;
while (parser.nextTag () != XmlPullParser.END_TAG)
     System.out.println("i get here");
     readMap(parser,i);
     i++;
parser.require(XmlPullParser.END_TAG, null, "webraska");
parser.next();
System.out.println("NOW get here");
parser.require(XmlPullParser.END_DOCUMENT, null, null);---------------------------
I know there is a lot of needless println's etc.. but i was going nuts trying to figure out what i should do :)
private void readMap(KXmlParser parser,int cde) throws IOException,XmlPullParserException
String [] a = new String[2];
a[0] = "status";
a[1] = "data";
System.out.println("ffffff " + cde);
parser.require(XmlPullParser.START_TAG,null, a[cde] );
String MapURL= null;
int inf = 0;
while (parser.nextTag() != XmlPullParser.END_TAG)
     inf++;
     parser.require(XmlPullParser.START_TAG, null, null);
     String name = parser.getName();
     String text = parser.nextText();
     System.out.println("bleh " + inf);
     if(name.equals("navid"))
     MapURL = parser.getAttributeValue(null,"latitude");
     System.out.println("go me" + MapURL);
     System.out.println ("<"+name+">"+text);
     parser.require(XmlPullParser.END_TAG, null, name);
System.out.println("wooohooo");
parser.require(XmlPullParser.END_TAG,null,a[cde]);
System.out.println("muha? "+ MapURL);
}

Similar Messages

  • Query on using kXML parser

    Hi everyone,
    I am writing code to parse a xml document using the kXML parser. My xml document consists of attributes within the tag. My code compiles but when i run i get org.kxml.io.ParseException.
    Something which i found was that, this exception occurs only when there is some attribute within the tag.
    Why is this happening. anyone can help me?
    I would be grateful
    Thanks

    I am using kxml as well to parse a xml file and it's attributes. It works great for me. The ParseException is probably only thrown when you got an illegal xml file (no correct format) I guess.
    But post some code and check your xml file.

  • How to use the kxml parser?

    I am getting problem in using the kxml parser.Actually my application is showing the java.lang.NoClassDefFoundError: org/kxml/parser/XmlParser error.
    Can you tell me how to use the kxml parser with our j2me application or what are the steps for this?
    Whether we have to use the kxml.zip or some other JAR file for this?
    Again whether we have to set any classpath for this?

    I was getting same error using kxml parser. The reason is losing interface in which constants are declared.
    You need to correct code of kxml a bit.
    In every place where constant from XmlPullParser interface is referenced only by its name (without reference to its class XmlPullParser) you need to change for use full name. it means changes like:
    START_DOCUMENT to XmlPullParser.START_DOCUMENT
    Everywhere.
    That's all!

  • KXML Parser

    Hi all,
    This question is for those of you who know and used the kXML parser (http://developers.sun.com/techtopics/mobility/midp/articles/parsingxml/)
    How can I use it in order to parse binary data which is stored in an XML (in the
    standard way, of course: CDATA)?
    attached is a copy of the xml file (it is an ordinary XML file, which
    contains a binary data between the tags: binaryImg).
    Thanks in advance,
    Alon<?xml version="1.0" encoding="utf-8" ?><D4UMProtocol><Session><id>551</id></Session><error><code>0</code><message></message></error><reportFeedback><msgType>1</msgType><msgTitle>it's weigh in day</msgTitle><msgContent>please step on your scale and report your weight</msgContent><binaryImg>![CDATA[PNG
    egfreefj44%%FFEdfedfefrttvsIENDB`]]</binaryImg></reportFeedback></D4UMProtocol>

    Yes, that one worked fine =) thx
    But now I have another problem (this time I add the code):
    Attribute att = null;
              String name = null;
              String address = null;
              KXmlParser parser = new KXmlParser();
              parser.setInput(is, null);
              Document document = new Document();
              document.parse(parser);
              Element root = document.getRootElement();
    int children = root.getChildCount();
         for (int i=0; i < children; i++) {
         if (root.getType(i) == Node.ELEMENT) {
         Element el = root.getElement(i);
         int babies = el.getChildCount();
         for (int j=0; j < babies; j++) {
              if (el.getType(j) == Node.ELEMENT) {
         Element elName = (Element)el.getChild(j);
         if (elName.getName().equals("name")) {
         att = elName.getAttribute("value");
         name = att.getValue();
         else if (elName.getName().equals("address")) {
         att = elName.getAttribute("value");
         address = att.getValue();
         System.out.println(name, address);
    Now I get an error msg that says that the class Attribute doesn't exist. I have looked in the api docs for the kxml parser (version 2.1.9) but I can't find anything about the Attribute class there. Should I use another class, e.g. Element, or what shall I do here? please help me =)

  • Plz help: org.kxml.parser.XmlParser$DefaultParserException

    Hello Friends,
    If I have received the following xml from the client via UDP:
    <SOAP-ENV:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/08/addressing">
    <SOAP-ENV:Header>
    <wsa:To>datagram://127.0.0.1:9090/soaprpc</wsa:To>
    <wsa:Action>urn:Services#echoString</wsa:Action>
    <wsa:MessageId>uuid:95946541-2ce-d590dbc-22e14a74</wsa:MessageId>
    <wsa:ReplyTo>
    <wsa:Address>http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</wsa:Address>
    </wsa:ReplyTo>
    </SOAP-ENV:Header>
    <SOAP-ENV:Body SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
    <echoString xmlns="urn:Services" id="o0" SOAP-ENC:root="1">
    <String xmlns="" xsi:type="xsd:string">a</String>
    </echoString>
    </SOAP-ENV:Body>
    </SOAP-ENV:Envelope>
    Does any one of you have any idea (or can see what i cannot may be :S) what could be the cause of the following exception when I use the method extractRoot(..) pasted below, to parse it? I am using kXML in J2ME environment.
    org.kxml.parser.XmlParser$DefaultParserException: Attribute name ressmust be followed by '='! @8:1764
    at org.kxml.parser.XmlParser.parseStartTag(+169)
    at org.kxml.parser.XmlParser.parseSpecial(+145)
    at org.kxml.parser.XmlParser.peek(+106)
    at org.kxml.kdom.Node.parse(+6)
    at org.kxml.kdom.Element.parse(+45)
    at org.kxml.kdom.Node.parse(+80)
    at org.kxml.kdom.Element.parse(+45)
    at org.kxml.kdom.Node.parse(+80)
    at org.kxml.kdom.Element.parse(+45)
    at org.kxml.kdom.Node.parse(+80)
    at org.kxml.kdom.Document.parse(+5)
    at cnsoap.server.UDPServerThread.extractRoot(+45)
    at cnsoap.server.UDPServerThread.await(+794)
    at cnsoap.server.UDPServerThread.run(+9)
    private void extractRoot(Datagram incomingPacket) throws IOException {
    // incomingPacket.getData() returns the xml I have pasted above
    InputStreamReader reader = new InputStreamReader (new ByteArrayInputStream(incomingPacket.getData()));
    XmlParser xp = new XmlParser(reader);
    Document doc = new Document();
    doc.parse(xp);
    root = doc.getRootElement(); // root is an instance member of the class
    Suggestions please :(
    Fahad Aijaz

    change your classpath

  • How to parse xml (kXML)

    I have some problems when I try to parse xml with the kXML parser. My xml doc looks like this:
    <?xml version="1.0" encoding="utf-8" ?>
    - <dsGreenRoom>
    - <Rooms>
    - <RoomsInfo>
    <ID>1</ID>
    <Name>Rum 101</Name>
    <Type>Dubbelrum</Type>
    <NumberOfBeds>2</NumberOfBeds>
    <Rate>980,00</Rate>
    <Currency>SEK</Currency>
    <Description>Ett genomtrevligt rum</Description>
    </RoomsInfo>
    - <RoomsInfo>
    <ID>2</ID>
    <Name>Mellanrummet</Name>
    <Type>Enkelrum</Type>
    <NumberOfBeds>1</NumberOfBeds>
    <Rate>650,00</Rate>
    <Currency>SEK</Currency>
    <Description>Ett litet tr?ngt rum i mitten</Description>
    </RoomsInfo>
    - <RoomsInfo>
    <ID>3</ID>
    <Name>Rum 102</Name>
    <Type>Flerb?ddsrum</Type>
    <NumberOfBeds>3</NumberOfBeds>
    <Rate>1250,00</Rate>
    <Currency>SEK</Currency>
    <Description>Ett ?nnu trevligare rum</Description>
    </RoomsInfo>
    </Rooms>
    </dsGreenRoom>
    And my code looks like this:
    KXmlParser parser = new KXmlParser();
                   parser.setInput(is, null);
                   Document doc = new Document();
                   doc.parse(parser);          
                   int child_count = root.getChildCount();
                   System.out.println("child = " + child_count + "\n");
                   for (int i=0; i < child_count; i++) {
              if (root.getType(i) == Node.ELEMENT) {
                   Element kid = root.getElement(i);
                        System.out.println("kid = " + kid.getName());
                   int babies = kid.getChildCount();
                   System.out.println("babies = " + babies);
                   for (int j=0; j < babies; j++) {
                        if (kid.getType(j) == Node.ELEMENT) {
                             Element room = kid.getElement(j);
                             System.out.println("room.getType() = " + room.getType(j));
                        if (room.getName().equals("ID")) {
              System.out.println("elName.getName() = " + room.getName());
              System.out.println("elName.geText() = " + room.getText(j));
              else if (room.getName().equals("Name")) {
              System.out.println("elName.getName() = " + room.getName());
              System.out.println("elName.geText() = " + room.getText(j));
                   } // end for(int j...)
              } // end if (root.getType(i)
              } //for (int i...)
    The problem is that I don't know how to get the values out of the tags:
    <ID>1</ID>
    <Name>Rum 101</Name>
    <Type>Dubbelrum</Type>
    <NumberOfBeds>2</NumberOfBeds>
    <Rate>980,00</Rate>
    <Currency>SEK</Currency>
    <Description>Ett genomtrevligt rum</Description>
    It's no problem to get the value from the firsts i.e. <ID> but I don't know how to get the value from <Name> ... <Description>. I have looked att examples but I don't understand how to do this. Can someone please help me =)

    okay, sorry, I only read the half of your problem ;-)
    You can read the content using the getText(0) method. the 0 indicates the number of the children which you want to get. That is always a 0 because you have always just one text-children in your text-tags. The content is again a children of type text!
    hth
    Kay

  • Problem parsing xml(J2ME Web Service spec) containing image in cldc/midp

    Hi,
    I have created a restful web service that generates xml file in app server. I have created xml file using JAXB2.1 spec. This xml file has many elements starting from char data to image (binary data). I could successfully create xml file and developed another test client to read the same file using JAXB. However, I am finding a problem while getting the image in the java me client (cldc1.1 and midp2.0).
    I am using J2ME Web Services Specification, using javax.xml.parsers.SAXParser to parse the xml file. Parsing is successful and got the character data. But the image data is not accurate, so I am not getting the image. I suspect the problem is with encoding but not sure how to solve this. At the server end, I verified that xml file is encoded with "UTF-8" encoding, not sure how to decode at the client end.
    I am totally confused as how to get the accurate image data, not sure if I use kxml parser would solve my problem.
    I would really appreciate if somebody can get back to me as this is very very important.

    Try to send to your web service the byte array instead of string and then convert the byte array into an image
    using a method like the following one in your service:
    // C# code
    public Image ByteArrayToImage(byte[] byteArrayIn)
         MemoryStream ms = new MemoryStream(byteArrayIn);
         Image returnImage = Image.FromStream(ms);
         return returnImage;
    }There can be some problem between encoding in J2ME and .Net so try different encodings in gathering the image bytes in your j2ME application, but, instead of jpg which has more encodings, try png that is a more standardized image compression(open standard).

  • Problems using kXml

    hi...
    am developing an application where i am using kxml parser.
    am using j2me wireless tool kit and palm emulator.
    while i try to compile my code in the tool kit, it gives error saying :
    c:\WTK104\apps\XMLTest\src\XMLTest.java:5: package org.kxml does not exist
    import org.kxml.*;
    ^
    am sure this problem is due to wrong placement of the package for kxml.
    i have downloaded kxml from the web and unzipped it. please tell me where to put that folder so that my application finds that .
    the import statement in my application is :
    import java.io.*;
    import java.util.*;
    import javax.microedition.lcdui.*;
    import javax.microedition.midlet.*;
    import org.kxml.*;
    import org.kxml.parser.*;
    thanks
    sanjib

    I used kXML in one of my projects in Eclipse and this is what I did to get it to work:
    Put the kXML JAR file in a folder that will not be included in the package for your project, i.e. NOT in src or lib or anything like that.
    Select your project in Eclipse and choose Configure Build Path.
    Select the Libraries tab and choose 'Add External JAR'.
    Now browse to the kXML JAR file and select it.
    This is the important part now. Now select the 'Order and Export' tab.
    You should see at least 3 entries (your project name, the J2ME Library and now kXML)
    Make sure there is a tick next to the kXML entry, this will tell Eclipse to include the files from the JAR whenever you build your project.
    Now if you select the 'Create Package' option for your project and check inside the created JAR file you should see all of the class files for kXML included in the correct paths.
    Never used anything other than Eclipse so I don't know how this translates, but if you know how to do something similar in the IDE you are using then that'll be the solution. Remember the important part of including the kXML JAR in the export otherwise it won't work.

  • Problems with kXMLParser (kXML 2)

    Hi colleagues,
    when I run my MIDlet which parses an XML file with the kXMLParser (kXML 2) I get the following exception:
    org.xmlpull.v1.XmlPullParserException: PI must not start with xml (position:unknown ���@1:7 in java.io.InputStreamReader@d590dbc)
         at org.kxml2.io.KXmlParser.exception(+47)
         at org.kxml2.io.KXmlParser.error(+42)
         at org.kxml2.io.KXmlParser.parseLegacy(+149)
         at org.kxml2.io.KXmlParser.nextImpl(+365)
         at org.kxml2.io.KXmlParser.next(+23)
         at org.kxml2.io.KXmlParser.nextTag(+4)
         at com.zesium.HelpParser.parse(+26)
         at com.zesium.HelpParser.openFile(+65)
         at com.zesium.HelpParser.run(+12)
    I don't understand what I did wrong. I serached for an explanation in the internet but I did not find anything.
    My XML file has the following structure:
    <?xml version="1.0" encoding="UTF-8" ?>
    <items>
    <item name="Funktionen">
    <paragraph>Text1</paragraph>
    </item>
    <item name="Programmbedienung">
    <paragraph>Text2</paragraph>
    <paragraph>Text3</paragraph>
    </item>
    </items>
    And my code is:
    public class HelpParser extends Thread {
    public void run() {
    openFile();
    public void openFile() {
         String helpResource = ResourceManager.getResourceString("help.file");
         InputStream in = this.getClass().getResourceAsStream("/res/"+helpResource);
         this.parse(in);
    public void parse(InputStream in) {
         // Initialize XML parser
         Reader reader = new InputStreamReader(in);
         KXmlParser kxmlParser = new KXmlParser();
         try {
              kxmlParser.setInput(reader);
              kxmlParser.nextTag();
              kxmlParser.require(XmlPullParser.START_TAG, null, "items");
              while (kxmlParser.nextTag() != XmlPullParser.END_TAG) {
                   readXMLData(kxmlParser);
              kxmlParser.require(XmlPullParser.END_TAG, null, "items");
              kxmlParser.next();
              kxmlParser.require(XmlPullParser.END_DOCUMENT, null, null);
         catch (XmlPullParserException xmlppe) {
              xmlppe.printStackTrace();
         catch (IOException ioe) {
              ioe.printStackTrace();
    private void readXMLData(KXmlParser parser) throws IOException, XmlPullParserException {
         String name = null;
         String paragraph = null;
         //Parse the element "item" in the XML file
         parser.require(XmlPullParser.START_TAG, null, "item");
         name = parser.getAttributeValue(null, "name");
         while (parser.nextTag() == XmlPullParser.START_TAG) {
              parser.require(XmlPullParser.START_TAG, null, "paragraph");
              paragraph = parser.nextText();
              parser.require(XmlPullParser.END_TAG, null, "paragraph");
         // Just for testing
         System.out.println("name: "+name);
         System.out.println("paragraph: "+paragraph);
    }     

    unlike johnson's c++ xml parser implementation, kxml is known to have problems with non-normalized xml tag patterns. kxml works like a charm with normalized structures. to solve the problem, we simply preprocess the byte stream to make it normalized -- by removing the rogue elements. however, avoid using stringbuffer in such kxml operations because it makes memory very volatile (you can see this in the sun mobility memory monitor). similar to QualComm's Brew operating system, the virtual machine does not do a stand-up job with garbage collection while using kxml. you should use GC whenever it is appropriate within the kxml parser code blocks.

  • KXML Error

    Hello i need some help here, i dont know what to do anymore. I'm using eclise and i'm trying to run my KXML Parser and i'm getting this error:
    Running with storage root C:\Documents and Settings\daniel\j2mewtk\2.5.2\appdb\DefaultColorPhone
    Running with locale: Portuguese_Brazil.1252
    Running in the identified_third_party security domain
    java.lang.NoClassDefFoundError: org/xmlpull/v1/XmlPullParserException
         at br.furb.furbot.mobile.MundoVisual.iniciarSequencia(+0)
         at br.furb.furbot.mobile.MundoVisual.iniciarSequencia(+6)
         at br.furb.furbot.mobile.exercicios.Teste.startApp(+37)
    I added the kxml jar on build path, what should i do to resolve this problem? The problem ocours when i run as a Java ME Midlet...

    SOLVED...
    Step 1:
    Eclipse -> "Project Properties" -> Java Build Path -> Add Jar (search .jar da KXML).
    Step 2: (Important!!!)
    On "build path" screen, go to the tab "_Order and Export_" , check the lib kxml2-xxxx.jar ,So now eclipse can see the .class files when Running as Middlet on the Emulator.
    Ty all
    Cya

  • Parsing WBXML POSt Request Data

    Hi!
    I want to read WBXML formatted SyncML data sent by a Mobile Device
    There is a servlets at server side which receives the http request of the
    device and tries to read the contents of the POST request data by using .
    Request.getInputStream(); method....
    I then Pass this data to a method "wbxmlToXml(req.getInputStream().toString().getBytes()) "
    I am using kxml as XML parsing the Initial Lines of the method are as following
    public static String wbxmlToXml(byte[] wbxml) throws IOException {
    String xml = null;
    try {
    // Construct an InputStream on byte[] to be used by WbxmlParser
    ByteArrayInputStream in = new ByteArrayInputStream(wbxml);
    AbstractXmlParser parser; //org.kxml.parser.AbstractXmlParser
    parser = new WbxmlParser(in);
    // Construct a DOM Document to parse WBXML
    Document document = new Document();
    document.parse(parser);------------------> Error :java.io.IOException: id 54 undef.
    I get "java.io.IOException: id 54 undef." error as mentioned above.
    Please somebody guide regarding this problem
    Regards,
    Maneesha

    The problem is solved! The error was in the post request. At the end of the query parameter was . For spa504,
    spa303,spa508 it was not important, but for spa525 important. Once I removed this parameter from the request, the phone immediately began to dial.
    Thanks for the help!
    That's a valid request for spa525G2:
    http://192.168.2.113/CGI/Execute
    POST / CGI / Execute HTTP/1.1
    Host: 192.168.2.113
    Accept: * / *
    Content-Type: text / xml; charset = "UTF-8"
    Content-Length: 92
    XML =

  • XML sending to Mobile Device with KXML + Bluetooth

    Dir Madame,
    Dir Sir ;-)
    I am using a N73, WTK22, EcipseME and KXML 2.3.0. I initalized a Bluetooth Connection between my mobile and my desktop application. So far, so well.
    It is possible to send simple String-Messages to my mobile device via DataOutputStream (dos) / DataInputStream (dis).
    dos.writeUTF("Hello Nokia Forum"); //ServerSide (=Desktop)
    print(dis.readUTF()); //prints "Hello Nokia Forum" on my Display. - ClientSide (=Mobile)
    But.. for sure, i need to send XML messages. Therefore, i send a XML File byte for byte from my desktop application to the mobile like this:
    boolean read = true;
         while (read) {
         byte b = dis.readByte();
         System.out.println(b);
         dos.write(b);
    catch(java.io.EOFException es){end of file reached..}
    If i print the bytes which are written to the outputStream (from desktop), for example, i get
    60
    63
    120
    109
    if i read them, on the client side, i get the same!
    60
    63
    120
    109
    - So, everything looks fine. But if i stop reading them out on the Client Side, and give the InputStream the XML Parser, i get an org.xmlpull.v1.XmlPullParserException
    Reader reader = new InputStreamReader(serverInputStream);
    KXmlParser parser = new KXmlParser();
    parser.setInput(reader);
    parser.nextTag(); //PullParserException..
    If i test my Code with
    InputStream in = new FileInputStream(url);
    where "url" is my XML file, KXML parses this direct InputStream. But if i read this InputStream and send it byte for byte to my mobile - KXML cannot read this..
    any ideas?

    Hi,
    As u told kXML can be used for devices like 6630 nokia. so i downloaded the jsr files of xml.plz tell me how to use kxml to make a xml file from a text file consisting of text and data residing on the device and send to the server to process it..for the time being tell me how to use kxml...any good documentation abt its usage in Netbeans IDE 6.1...
    regards,
    sanjay

  • NoClassDef kxml

    Could somebody tell me why I'm getting this error. I downloaded the kxml parser to use in the sprint wireless developer kit. I know what it means but I just can figure out how to fix it.
    Uncaught exception java/lang/NoClassDefFoundError: org/kxml/parser/XmlParser

    It may be the issues with your parsing logic..
    Could you provide your parsing code..
    Regards,
    Raja Nagendra Kumar

  • Parameters from midlet to servlet

    Hi all,
    i have been trying to pass values from MIDlet (setRequestProperty(); ) and to servlet (request.getParameter();).
    but when i tried to print out the value, it just contained NULL value.
    I had a look at the java forum website, there were plenty of same problems and no one got right.
    I'll really appreciate it if anyone fixes this for me.
    ---------------------MIDLET-----------------------------------------------------------------------------
    import javax.microedition.midlet.*;
    import javax.microedition.lcdui.*;
    import javax.microedition.io.*;
    import java.io.*;
    import java.util.*;
    import org.kxml.*;
    import org.kxml.parser.*;
    public class MbankMIDlet  extends MIDlet implements CommandListener {
      private Display display;
      private Form loginForm = new Form("Login");
      private Form mainForm = new Form("MobileBank");
      private String loguserID;
      private String logpass;
      private String mSession;
      private StringItem stringItem = new StringItem(null,"");
      private TextField userIDTextField = new TextField("User ID", "", 8, TextField.NUMERIC);
      private TextField passwordTextField = new TextField("Password", "", 12, TextField.PASSWORD);
      static final Command loginCommand = new Command("Login", Command.OK, 1);
      static final Command exitCommand = new Command("Exit", Command.STOP, 1);
      static final Command backCommand = new Command("Back",Command.BACK, 1);
      public MbankMIDlet() {
        mainForm.append(stringItem);
        mainForm.addCommand(exitCommand);
        mainForm.addCommand(backCommand);
        mainForm.setCommandListener(this);
      public void startApp() throws MIDletStateChangeException {
        display = Display.getDisplay(this);
        loginForm.append(userIDTextField);
        loginForm.append(passwordTextField);
        loginForm.addCommand(loginCommand);
        loginForm.addCommand(exitCommand);
        loginForm.addCommand(backCommand);
        loginForm.setCommandListener(this);
        display.setCurrent(loginForm);
      public void destroyApp(boolean unconditional) {
        notifyDestroyed();
      public void mainMenu() {
        display.setCurrent(loginForm);
      public void pauseApp() {
        display = null;
        loginForm = null;
        mainForm = null;
        stringItem = null;
        userIDTextField = null;
        passwordTextField = null;
      public void commandAction(Command c, Displayable d) {
        String label = c.getLabel();
        if (label.equals("Exit")) {
          destroyApp(true);
           mSession = null;
        } else if (label.equals("Login")) {
          login();
        } else if (label.equals("Back")){
          mainMenu();
      private void login() {
        loguserID = userIDTextField.getString();
        logpass = passwordTextField.getString();
        Form waitForm = new Form("Waiting...");
        display.setCurrent(waitForm);
        Thread t = new Thread() {
          public void run() {
            connect();
        t.start();
      private void connect() {
        HttpConnection hc = null;
        InputStream in = null;
        OutputStream os = null;
        String url = getAppProperty("MbankMIDlet.URL");
        try {
          hc = (HttpConnection)Connector.open(url);
          hc.setRequestMethod(HttpConnection.GET);
          hc.setRequestProperty("User-Agent", "Profile/MIDP-1.0 Configuration/CLDC-1.0" );
          hc.setRequestProperty("Content-Language", "en-US" );
          hc.setRequestProperty("Accept", "text/plain");
          hc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded" );
          hc.setRequestProperty("Connection","close");
          hc.setRequestProperty("loguserID", loguserID);
          hc.setRequestProperty("logpass", logpass);
          os = hc.openOutputStream();
          os.close();
    //      os.flush();  //tried close() and flush() but none of them worked.
          if (mSession != null) {
              hc.setRequestProperty("Cookie", mSession);
          // Read the session ID from a cookie in the response headers.
          String cookie = hc.getHeaderField("Set-cookie");
          if (cookie != null) {
              int semicolon = cookie.indexOf(';');
              mSession = cookie.substring(0, semicolon);
          in = hc.openInputStream();
          int rc = hc.getResponseCode();
          if( rc == HttpConnection.HTTP_OK ) { //HTTP_OK equals 200
            System.out.println("HttpConnection OK");
            StringBuffer xmlBuffer = new StringBuffer();
            String xmlString = null;
            int ch;
            while ( ( ch = in.read() ) != -1 )
              xmlBuffer.append( ( char )ch );
            xmlString = xmlBuffer.toString();
            stringItem.setText(xmlString);
          else if (rc == HttpConnection.HTTP_UNAUTHORIZED){//HTTP_UNAUTHORIZED equals 401
            System.out.println("HttpConnection Unauthorized");
            int contentLength = (int)hc.getLength();
            byte[] raw = new byte[contentLength];
            int length = in.read(raw);
            String s = new String(raw,0,length);
            stringItem.setText(s);
          in.close();
          hc.close();
        catch (IOException ioe) {
          stringItem.setText(ioe.toString());
        finally {
          display.setCurrent(mainForm);
    }---------------SERVLET----------------------------------------------------------------------------
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.util.*;
    import java.io.*;
    public class LoginServlet extends HttpServlet {
        public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
              HttpSession session = request.getSession();
              response.setContentType("text/plain");
              PrintWriter out = response.getWriter();
              String userID, password, userRole = null;
              try {
                                  userID = (String)request.getParameter("loguserID");
                  password = (String)request.getParameter("logpass");
                  System.out.println(userID); // "Null printed"              System.out.println(password);  // "Null printed"
              catch (Exception e) {
                   //If anything goes wrong, print the Exception message
                  e.printStackTrace(out);
    }Thanks.

    getParameter() can't parse the input stream well if there is any issues in the sent content. this is true, with varying mobile phone http impl.
    You would find the content at servlet, by using request.getInputStream() and reading the entire content.
    Here is the sample code:
    public static String readMobileData(final HttpServletRequest aRequest) throws Exception
         String lData = null;
         Enumeration params = aRequest.getParameterNames();
         while (params.hasMoreElements())
         //from real Nokia 6600 Mobile the request is sent as param, though
         //it is post
         String lName = params.nextElement().toString();
         lData = aRequest.getParameter(lName);
         System.out.println("\nParameter:" + lName + "=" + lData);
         if (lData == null)
         //in emulator the data is coming as inputstream
         ServletInputStream in = aRequest.getInputStream();
         DataInputStream dIn = new DataInputStream(in);
         lData = dIn.readUTF();
         lData = lData.substring(lData.indexOf("=") + 1);
         System.out.println("Stream Request:\n" + lData);
         return lData;
    Regards,
    Raja Nagendra Kumar,
    C.T.O,
    When Teja is Tasked, the Job Gets Done
    www.tejasoft.com

  • Error at the time of defining XmlParser object in J2ME......

    Hi:
    I want to use XmlParser in my J2ME application, but at the time of defining XmlParser object i a getting error is:"XmlParser cannot be resolved to a type". I am using eclipse for developing application. I have already added KXml.zip in my src folder.
    I have imported following things:
    import javax.microedition.lcdui.*;
    import javax.microedition.midlet.*;
    import java.io.*;
    import javax.microedition.io.*;
    import javax.microedition.rms.*;
    import org.kxml.*;
    import org.kxml.parser.*;
    and actual error line is:
    byte[] xmlByteArray = str.getBytes();
                                  ByteArrayInputStream xmlStream = new ByteArrayInputStream(xmlByteArray);
                                  InputStreamReader xmlReader = new InputStreamReader( xmlStream );
              //error line          XmlParser parser = new XmlParser( xmlReader );
    So, can anybody help me.
    Thank You

    Hi AnupDesai.
    I'm using [kXML 2|http://kxml.sourceforge.net/kxml2/] parser, so maybe this could help you. I'm using NetBeans 6.5 and to use it I had to add the JAR file into the "resources" of my project. Then I simply use three imports:
    import org.kxml2.io.KXmlParser;
    import org.xmlpull.v1.XmlPullParser;
    import org.xmlpull.v1.XmlPullParserException;And use it like this:
    KXmlParser parser = new KXmlParser();
    InputStreamReader reader = (open your streeam here);
    parser.setInput(reader)I hope this helps you!
    Marc

Maybe you are looking for

  • Can't download podcast into my iPod mini

    normally I just plug my iPod into my Mac when I wake up in the morning. Then everything is done for me. Usually all I have to do is hit the "update to iPod" from file menu and I'm finished. Well this morning, nothing is working at all!?!? HELP!!!!!!

  • How to install + where to get: JDBC-drivers for Oracle8i

    hi, i need to install the JDBC drivers (to use oracles XSU). where can i get them (for oracle 8i) and how do i install them. im not familiar with java so im looking for a step-by-step install-manual. thanks in advance

  • Batch number as po number

    hello all, i have a requirement like in place of batch number i need to print po number either while creating po or while shiipping so i need the exit for that .

  • How do you fix imported iCal duplicate events?

    I just downloaded and imported the latest Nascar Sprint Cup 2012 iCal calendar. I imported it as a NEW calendar. My calendars are PUSHED from iCloud. I've found notices pushed out to my iPhone and iPad are also often duplicated as well but only enter

  • Don't want to loose time machine back ups after Lion

    Hi All.  When I got my new MBP, I used my time machine backup during instillation to transfer files and settings from my previous MacBook.  Now, my time machine backups only go as far back as when I got my new computer.  All the previous back ups tha