Connecting your J2ME application to the internet – Part One


In the last tutorial I did some code snippets on how to connect your J2ME application to the internet but judging from the response I got I seem to have lost many people. In this tutorial I am going to guide you step by step on how to build an application and connect it to a server. The tutorial will be broken into three parts namely

  1. Building the web services on the server ( I will be using PHP to do this)
  2. Creating a parser in J2ME for the web services generated in part one
  3. Using the parser to fetch and display the data on our application

Without wasting time let us dive into the first part; building the required web services.
Building the web services
A J2ME application can’t consume data directly from the web and so we have to pass data to it in a specified format so that it is able to pass it. Web pages have too much data and the data is normally poorly structured. We have to ways of providing highly structured data

  •  JSON
  • XML – SOAP or Restful web services

I will not go much into the details of the above technologies but if you are really interested there are so many resources online. For this tutorial I will be using user generated XML. JSON is far much easier to generate and consume but I will use that in a later tutorial.
Our application will enable a user to login to an online server; you can add more functionality later. As a result I am going to use Joomla CMS for all the back end stuff as user management has been automated. The assumption is that you know how to install Joomla and configure it. I am going to modify the Joomla user component so that we can make queries to it from our application and it returns data in xml format. After login we will just display the user information.
Step 1
Install Joomla, any version can work but installing the latest version is recommended.  The last J2ME project I did was in Joomla 1.5 so I will use the same code. I have therefore installed Joomla 1.5 on my machine.
Step 2
After you have successfully installed Joomla navigate to the site folder. The site folder looks like the screen shot below

Folder structure

Folder structure

Navigate into the components folder and open the component named com_user. Once inside this folder open controller.php using your favorite editor. I am using Eclipse but any editor works. Extensions in Joomla are built using the MVC (Model-View-Controller) convention.You will find several methods in this class. We are going to introduce one more method; loginPhone(). We will make a call to this method and pass to it a username and password. If the username+password combination matches then we will get an xml feed containing the user details. If they don’t match the xml will return zero as the user id. The code is as shown below
functionloginPhone()
{
// Check for request forgeries
//JRequest::checkToken(‘request’) or jexit( ‘Invalid Token’ );

global$mainframe;
/*the lines below are used by joomla to determine where to redirect the user after successful login */
if($return = JRequest::getVar(‘return’, ”, ‘method’, ‘base64’)) {
$return = base64_decode($return);
if(!JURI::isInternal($return)) {
$return = ”;
}
}
/*the options array will not be used here. It is normally for the browser and allows the user
to specify options like rememmber me */
$options = array();

$options[‘remember’] = JRequest::getBool(‘remember’, false);
$options[‘return’] = $return;

$credentials = array();
/* JRequest is similar to $_$_REQUEST. We use getVar when we are not sure what format the data we are getting is
Other options are getString and getInt */
$credentials[‘username’] = JRequest::getVar(‘username’, ”);
$credentials[‘password’] = JRequest::getString(‘passwd’, ”);
//create an instance of the database object
$db=JFactory::getDBO();
/* build our query. Before we try to login the user let us check if he/she is in the sessions table */
$query=”SELECT session_id AS sid,userid FROM #__session WHERE username='”.$credentials[‘username’];
//set the query
$db->setQuery($query);
/* fetch the result. We are using loadObject since we expect one result. For more information check the Joomla API */
$sess=$db->loadObject();
if($sess->userid>0){
/* using the user id from the session table let us fetch the user details from the user table */
$user=JFactory::getUser($sess->userid);
$query=”SELECT myusertype FROM #__users WHERE id={$user->id}”;
$db->setQuery($query);
$usertype=$db->loadResult();
/* let us now build our xml. we start by defining the encoding and version */
$returnXml  ='<?xml version=”1.0″ encoding=”iso-8859-1″?>’;
/* the opening tag. You should be very careful with xml, it is very strict */
$returnXml .='<user>’;
//let us now insert our data
$returnXml .='<userid>’.$user->id.'</userid>’;
$returnXml .='<name>’.$user->name.'</name>’;
$returnXml .='<email>’.$user->email.'</email>’;
$returnXml.='<usertype>’.$usertype.'</usertype>’;
//close the opening tag
$returnXml .='</user>’;
header(“Content-type: text/xml; charset: iso-8859-1″);
//the lines below are required.
ob_start();
//we echo the xml we created
echo$returnXml;
/* cautionary measure to make sure that the xml is flushed to display */
ob_flush();
/* exit makes sure that we are not redirected to the browser */
exit;
}else{
/* preform the login action since we have determined the user is not in the session table */
$error = $mainframe->login($credentials, $options);

if(!JError::isError($error))
{

$returnXml  ='<?xml version=”1.0″ encoding=”iso-8859-1”?>’;
$returnXml .='<user>’;
$user=JFactory::getUser();
$session =&JFactory::getSession();
$returnXml .='<token>’.$session->getToken().'</token>’;
$returnXml .='<sessid>’.$session->getId().'</sessid>’;
$returnXml .='<userid>’.$user->id.'</userid>’;
$returnXml .='<name>’.$user->name.'</name>’;
$returnXml .='<email>’.$user->email.'</email>’;
$returnXml .='</user>’;
header(“Content-type: text/xml; charset: iso-8859-1″);
ob_start();
echo$returnXml;
ob_flush();
exit;
}
//login credentials don’t match
else
{
$returnXml  ='<?xml version=”1.0″ encoding=”iso-8859-1”?>’;
$returnXml .='<user>’;
$returnXml .='<userid>0</userid>’;
$returnXml .='</user>’;
header(“Content-type: text/xml; charset: iso-8859-1”);
ob_start();
echo$returnXml;
ob_flush();
exit;
}
}
}
The above code is not wellformatted; at the end of the tutorials I will upload the entire project on Git.A note about the way we are constructing the sql statements; we are not calling the actual table name but rather prefixing with #__. This is Joomla’s convention and it will be replaced by the database prefix set when we installed Joomla.
Step 3
The above function can be accessed using the browser. In my case I would use a url like

It all depends on the technology you are using so all you need to do is find out how to invoke a method and pass parameters to it. You can download the tutorial in pdf format here
What Next
In the next tutorial we will create a J2ME parser and then make a call to our method with several parameters from the app. Cheers!

Advertisements

3 thoughts on “Connecting your J2ME application to the internet – Part One

  1. Greetings,

    I am a novice web developer but have a joomla powered website (latest version 3.15) I am very very interested to know how I can create a java (j2me) app and integrate it with my site. I am interested in only j2me because I am in africa and up to now this is the software that a vast majority of phones (including mine!) can handle. Any assistance is HIGHLY appreciated.

    • Hey Don. You need to create web services to expose your site’s function. Web services are just functions that expose your site functionality in either JSON, WSDl or XML. From there you will be able to parse the information and display information on the phone app. There are many parsers out there. I would recommend JSON

      • Thanks for the quick response. I have been researching all week on this and there seems like a hell lot to learn.though I am very willing to. However, I am just realising now that maybe I should have used a different term than “novice” or “web developer” because most of what you said sounds like Greek to me! My research has let me to a site call http://www.ownmidlet.com which seems very interesting, however experienced developers such as you can still provide vital input to guide beginners like myself. I have already made my own midlet on that site but annoyingly it opens up my site using the default mobile phone browser then I get some errors. Once again Kiruikenn, I very much appreciate your input but if you may in laymen’s language or links to simple online tutorials, how can I make an j2me app that can 1) interact with my joomla website and 2) open using maybe operamini 4.4 instinct which is another j2me app in itself.

        Thanks,

        Don.

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s