Blog Post: J2ME Tutorials
J2ME Tutorials: Part 3: J2ME Basics (Event Handling)
Author:Sanjeev Maharjan

In our previous tutorial, we had used IMPLICIT menu type to create menu as above, nothing will happen even though we select the menu option. We need to perform event handling to handle such selection action. Also, in the form part we can add event listeners to check if any changes occur to form elements or any command is selected from the form. So, our next task is to create a listener which would handle such events.

The list of Event Listener Interfaces that will be demonstrated in this tutorial:

javax.microedition.lcdui.CommandListener
javax.microedition.lcdui.ItemStateListener

Events generated by such IMPLICIT list and Command objects, added into the form, can be handled by implementing CommandListener Interface. Similarly the change in state of the form elements can be handled by implementing ItemStateListener Interface. Hence we will be creating listener which implements CommandListener and ItemStateListener.

CommandListener defines a method prototype:

public void commandAction(Command cmd, Displayable dsp)
where cmd represents the source of event, and dsp represents the displayable item where this event generated

ItemStateListener defines a method prototype:

public void itemStateChanged(Item itm)
where itm represents the form element whose change in state generated the event

By implementing Event handling, we would be developing following flow in our MIDlet Application:

event-flowBesides that, when the form object is loaded, we will handle the change of state events in textfield and the choicegroup objects. We will display an alert msg if a user enters a number in textfield saying that no number is allowed and with change the choicegroup state, we will alert the selected Gender content.

Alert screen is a displayable component in J2ME, which displays data to the user and waits for a while before proceeding onto the next Displayable component specified.

To create Alert screen in J2ME we use following constructor:

public Alert(String title)

To set the content of Alert screen we use following method:

public void setString(String content)

To display Alert Screen we use following method of Display object:

public void setCurrent(Alert obj,Displayable next)
where next represents the next displayable component after the alert screen closes.

Let us now create our class MyCommandListener that implements CommandListener and ItemListener, where the events are handled as specified above in MyCommandListener.java:

import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.ItemStateListener;
import javax.microedition.lcdui.List;
import javax.microedition.lcdui.Item;
/*Creating our Event handling class that implements CommandListener and ItemStateListener*/
public class MyCommandListener implements CommandListener,ItemStateListener{
private MyFirstApp mainApp;
//Passing the MIDlet object to the Event handling code
public MyCommandListener(MyFirstApp app)
{
mainApp=app;
}// end of Constructor
/*Function to handle the events triggerred by changes in state of form elements*/
public void itemStateChanged(Item itm)
{
//If TextField content is changed
if(itm.getLabel()=="Name")
{
String str=mainApp.getName();/*getName returns content of TextField*/
boolean flag=true;
for(int i=0;i<str.length();i++)
{
if(Character.isDigit(str.charAt(i)))//Checking if textfield contains numbers
{
flag=false;
break;
}
}
if(!flag)//means there is number in the textfield
{
//Creating Alert object with Title ‘Error in TextField'
Alert obj=new Alert("Error in TextField");
obj.setString("Cannot Have Numbers in the Field");
/*retrieve the current displayable i.e.Demo Form and store it in variable ‘next'*/
Display display=Display.getDisplay(mainApp);
Displayable next=display.getCurrent(); //current displayable stored in next
/*setting Alert object as current display and Demo Form as next Displayable after the Alert Obj is displayed*/
display.setCurrent(obj,next);
}
}
else if(itm.getLabel()=="Gender")
{
/*Creating Alert Object to Display Current Gender Value*/
Alert obj=new Alert("Change in Gender");
obj.setString("Current Gender:"+mainApp.getGender());
/*retrieve the current displayable i.e.Demo Form and store it in variable ‘next'*/
Display display=Display.getDisplay(mainApp);
Displayable next=display.getCurrent();
/*setting Alert object as current display and Demo Form as next Displayable after the Alert Obj is displayed*/
display.setCurrent(obj,next);
}
}
public void commandAction(Command cmd,Displayable dsp)
{
//Check if the event source displayable is Main Menu of not
if(dsp.getTitle()=="Main Menu")
{
/*If Main Menu Option is Implicit the option are associated with SELECT_COMMAND so checking if the event is triggered by selecting menu option*/
if(cmd==List.SELECT_COMMAND)
{
switch(mainApp.getSelectedMenu())
{
case 0://which means u selected Open Demo
Display display=Display.getDisplay(mainApp);
//setting Demo Form as Current Display for MIDlet
display.setCurrent(mainApp.getForm());
break;
case 1://which means u selected Exit
mainApp.destroyApp(true);
break;
}
}
}
/*Check If Event is triggered from My Demo Form*/
else if(dsp.getTitle()=="My Demo Form")
{
//Check if Event Source is backCommand
if(cmd==mainApp.backCommand)
{
Display display=Display.getDisplay(mainApp);
//set Main Menu as current Display
display.setCurrent(mainApp.getMainMenu());
}
//Check if Event Source is okCommand
else if(cmd==mainApp.okCommand)
{
//Create Alert Screen to Display Form Contents
Alert obj=new Alert("Form Inputs:");
obj.setString("Name:"+mainApp.getName()+"nGender:"+mainApp.getGender());
Display display=Display.getDisplay(mainApp);
Displayable next=display.getCurrent();
//Display the Alert Screen and come back to Demo Form
display.setCurrent(obj,next);
}
}
}
}


Now that we have create the event handling code also, we have to register that event handler to the Main Menu List and Form. Following are the updated codes for getForm() and getMainMenu() with the registration of event handler:

public Displayable getMainMenu()
{
//Create Main Menu
mainmenu =new List("Main Menu",Choice.IMPLICIT);
mainmenu.append("Open Demo", null);
mainmenu.append("Exit", null);
MyCommandListener comListener=new MyCommandListener(this);
//Creating and Registering Listener for the Main Menu Component
mainmenu.setCommandListener(comListener);
return mainmenu;
}
public Displayable getForm()
{
//creating a form with textfield, textbox, radio buttons
form=new Form("My Demo Form");
//creating blank textfield with label Name of size 30
txtField=new TextField("Name","",30,TextField.ANY);
//Creating exclusive choicegroup with label Gender
cGroup=new ChoiceGroup("Gender",ChoiceGroup.EXCLUSIVE);
//Appending items to the choicegroup male and female
cGroup.append("Male",null);
cGroup.append("Female",null);
//creating command to navigate back
backCommand=new Command("Go Back",Command.BACK,2);
//creating command to process form
okCommand=new Command("DONE",Command.OK,1);
//adding commands to form
form.addCommand(backCommand);
form.addCommand(okCommand);
//adding form elements to form
form.append(txtField);
form.append(cGroup);
//creating and register listeners for the form
MyCommandListener comListener=new MyCommandListener(this);
form.setItemStateListener(comListener);
form.setCommandListener(comListener);
return form;
}
Additional functions created inside MyFirstApp MIDlet to retrieve the values of List menu, textfield and choicegroup are as follows:
public int getSelectedMenu()
{
return mainmenu.getSelectedIndex();
}
public String getGender()
{
return cGroup.getString(cGroup.getSelectedIndex());
}
public String getName()
{
return txtField.getString();
}

With this, tutorial on J2ME event handling demonstration is completed. This also concludes our Basic J2ME Tutorials. In the upcoming tutorials, I will show how to develop a Mobile Game named GetThePicture. Till Then Keep Coding...

 

 

COMMENTS

No Comments Yet

Post a comment
* marked are required fields
*Name:
*Email Address:
*City:
*Comments
In order to help us prevent automated submissions, please type the number shown in below picture
*Validation no.
captcha
My Latest Tweets
Download Archive Here:
Twitter LinkedIn Blogger Behance Portfolio Facebook