Connecting your J2ME application to the internet – Part Three

In this tutorial I will introduce the KXML Parser and use it to parse data from our server.  The parser will use the Person’s class we did in our last tutorial to manipulate the data we will obtain from the server and store it. Let us straight away dive into it. We are still using theJ2ME project we created in the last tutorial.

The Steps

Step one

Download the latest KXML parser. You will get a jar file which we will include in our project. For this tutorial I will be using kxml2-2.3.0 which I am positive is not the latest version. Right click on the Resources folder in your J2ME project and select the Add Jar/Zip option. Navigate to where your KXML jar file is and add it to your project. For purposes of project portability I have copied the jar file to the root folder of my project but you can have it anywhere. My root project folder looks as follows

The project root folder

The project root folder

Now that we have KXML in our project we can utilize the methods exposed by the class.

Step two

Before we do any parsing we need to include LWUIT in our project. For the tutorial I am using LWUIT 1.4. Download LWUIT here. To include it in your project right click on the Resources folder in your project select the Add Jar/Zip option and navigate to location of the LWUIT jar file. I have copied it to my project folder for purposes of project portability.

Step three

Now what we need to do is create a class specifically dedicated to parsing any content that we fetch from the online server. In the same package that we created the Person’s class let us create a class and name it KxmlRssParser. You can use any name but for the purpose of the tutorial that is the name I will use. My project tree structure looks as follows

The project structure

The project structure

Step four

In the KxmlRssParser the first thing we do is create a constructor without any parameters. The code segment below shows how this achieved.

  • public KxmlRssParser(){       }

In later steps we might add some initialization in the constructor.  Create a method with the following signature

  • public Person loginParser(final String name, final String pass)

The method takes two arguments; the username and password and returns an object Person. The object will contain the user data if login is successful. The code segment below should be placed in this method. I have done my best to comment it in each step so that you can understand what it does

package com.kirui.parser;

import com.sun.lwuit.Dialog;

import com.sun.lwuit.Display;









import org.xmlpull.v1.XmlPullParser;



* @author Kirui


public class KxmlRssParser {


* The string below holds our base url so that we only append the action that we need at the end


static String HOME = “http://localhost/j2me_demo/index.php?option=”;


* empty constructor. you can do all your initializations here if there are any


public KxmlRssParser() {



* method to login a user to our online system from the mobile application

* @param name the username

* @param pass the user password

* @return an instance of the class Person with the data we requested


public Person loginParser(final String name, final String pass) {


*create an instance of the Person class. We will add the user data to this object

* at the end of the method we will return this object to the method that made the call


final Person item = new Person();


* We are creating a separate thread from the main thread to pull the data we need

* LWUIT has its way of doing this; by making a call to Display.getInstance().invokeAndBlock(new Runnable()

* we are creating a new thread


Display.getInstance().invokeAndBlock(new Runnable() {


* we do all our manipulation in the run() method as defined by the Runnable interface


public void run() {

//instance of the KXmlParser class

KXmlParser parser = null;


*we use HttpConnection to communicate with the online server. You can also use HttpsConnection


HttpConnection conn = null;

//InputStream and InputStreamReader are used to read the data we fetch

InputStream rssStream = null;

InputStreamReader isr = null;

//the request might throw an error so we use a try and catch statement

try {

parser = new KXmlParser();

//append our base url (HOME) to url so that we have the complete url toio make our request

String url = HOME + “com_user&task=loginPhone&username=” + name + “&passwd=” + pass;

//open an httpconnection with our url as the arguement

conn = (HttpConnection);


* specify how we are sending information. We can use GET or POST but since we are sending a small amount of

* data and getting some back the best option is GET




* setRequestProperty sets the agent type. Profile/MIDP-1.0 Configuration/CLDC-1.0 tells the

* communication protocol that the request is being made from a mobile application

* it is absolutely neccessary that you set this


conn.setRequestProperty(“User-Agent”, “Profile/MIDP-1.0 Configuration/CLDC-1.0”);


* we can get several responses from the server. using the getResponseCode() method

* we are able to know which one we got. HttpConnection.HTTP_OK indicates that the connection was

* successful so we can proceed. Other response codes are HttpConnection.HTTP_BAD_GATEWAY,

* HttpConnection.HTTP_CLIENT_TIMEOUT and many more all giving us the response type given

* by the server in question


if (conn.getResponseCode() == HttpConnection.HTTP_OK) {

//the string below will hold the input stream from the server.

String str;

//we are opening the input stream and retrieving data from it

rssStream = conn.openInputStream();

//check lenght of input stream

int lenght = (int) conn.getLength();

//there are two ways of parsing depending on the server response

if (lenght != -1) {

byte serverData[] = new byte[lenght];;

str = new String(serverData);

} else {

ByteArrayOutputStream bStrm = new ByteArrayOutputStream();

int ch;

while ((ch = != -1) {



str = new String(bStrm.toByteArray());



byte[] payload = str.getBytes();

ByteArrayInputStream bain = new ByteArrayInputStream(payload);

isr = new InputStreamReader(bain);



//to start parsing we need to specify the start tag,our start tag is <user>

parser.require(XmlPullParser.START_TAG, null, “user”);


//we are going to parse until we encounter </user> tag

while (parser.getEventType() != XmlPullParser.END_TAG) {

String nodeName = parser.getName();


* the parsing is done by checking if a tag exists. for example in

* the first if below it will check if the <userid> tag exists using

* nodeName.compareTo(“userid”)method. If it does it

* picks the value using parser.nextText() method and then using the setter method

* we created in our class we append this text to our object


if (nodeName.compareTo(“userid”) == 0) {


} else if (nodeName.compareTo(“name”) == 0) {


} else if (nodeName.compareTo(“email”) == 0) {


} else if (nodeName.compareTo(“username”) == 0) {


} else {






} catch (Exception ioe) {“Error”, “Error connecting to the internet”, “Exit”, null);


} finally {

try {

if (isr != null) {



if (rssStream != null) {



if (conn != null) {



} catch (IOException i) {






return item;



Please pay attention to the imports that we are making as one mistake will lead to the code not working at all. You can download the pdf version of the tutorial here

What Next?

In the next tutorial we are going to build the J2ME application with the login interface and then finally connect to the online server and login.


One thought on “Connecting your J2ME application to the internet – Part Three

  1. Pingback: Connecting your J2ME application to the internet – Part Four | KiruinC

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s