Click here to Skip to main content
Click here to Skip to main content

J2ME: Using TextFields and Alerts

, 12 May 2011
Rate this:
Please Sign up or sign in to vote.
This is a J2ME beginner article that describes how to use different J2ME components in your application to make it more user interactive, using TextField and Alerts UI components.

Introduction

User Input and Notification Messages are one of the most important things in Interactive Applications, and mobile applications is one type of these applications. In this article, you will learn how to use the text field and alert UI components to create the "User Registration" J2ME application. The text field is an editable text component that is used to accept input from user. On the other hand, the alert is a displayable screen that is used to present various kinds of information to the user for a certain period of time before proceeding to the next displayable.

For more information about creating MIDlet class, Form and Commands in J2ME applications, you can read the following articles:

The "User Registration" application is a simple application that asks for user information and displays an alert notification about registration completion. In future articles, you will learn how to validate user input and save this information for later use. The application consists of a main form that contains five text field items. These text field items allow the user to enter the required registration fields which are email, password, name, mobile and website. The form also has two commands, OK and Exit commands. OK command displays a registration complete notification Alert for five seconds, it also uses the entered name to thank the user. 

Following is a screenshot of how the final application will look like:

Figure: Application screenshot

Creating Form Components

To create your form components, you will start by creating the text field items. The text field item can be created using an instance of TextField class where you need to specify four values:

  • The label that is a string value used to describe the accepted user input.
  • The text which is the initial content of the field and can be null for empty content.
  • The maximum size that specifies the maximum allowed number of characters the user can enter in the field.
  • And the input constraints which are used to restrict the user's input by a variety of ways. For example, if you pass the NUMERIC constraint, the application will allow the user to enter only numeric characters.

Let's start creating the form components which are five text field items and two commands. To do that, you will add five TextField data members for email, password, name, mobile and website fields.

public class UserRegistration extends MIDlet implements CommandListener {
    //...
    private TextField emailTxt;
    private TextField passwordTxt;
    private TextField nameTxt;
    private TextField mobileTxt;
    private TextField urlTxt;

    private Command okCmd;
    private Command exitCmd;
    //...
} 

The next step is to create an instance of TextField class for each TextField data member and pass the four parameters (label, text, maximum size and input constraints). The first text field item uses EMAILADDR constraint to allow the user to enter email address and the second item uses PASSWORD which indicates that the text entered is confidential data and should not be displayed. The name text field item uses ANY constraint to indicate that this field has no constraints, the mobile item uses PHONENUMBER constraint which allow only numeric characters in addition to some characters like + and finally the website item uses URL to allow the user to enter a website address.

public UserRegistration() {
    //...
    emailTxt = new TextField("Email:", "", 100, TextField.EMAILADDR);
    passwordTxt = new TextField("Password:", "", 16, TextField.PASSWORD);
    nameTxt = new TextField("Name:", "", 50, TextField.ANY);
    mobileTxt = new TextField("Mobile:", "", 15, TextField.PHONENUMBER);
    urlTxt = new TextField("Website:", "", 100, TextField.URL);
} 

Create Form and Add Components

As we discussed in the last article, there are two ways for adding components to a form, the first using the Form class append() method which can be used in case of a small number of components or when you need to add components after form creation. The second way is using the constructor by passing an array of type Item class that contains all the items to be added.

As you have five items to be added to the form, you will use the constructor by creating an array of type Item that contains all five items and then pass it to the constructor.

public UserRegistration() {
    //...
    registrationFrm = new Form("User Registration", new Item[] 
			{emailTxt, passwordTxt, nameTxt, mobileTxt, urlTxt});
}

Create the Alert

One of the methods used to alert the user in J2ME is the Alert displayable, which can be displayed after specifying four values:

  • The title that must be passed when creating the alert as a string.
  • The text which is the message that is displayed to the user.
  • The image that provides an indication of the alert type.
  • The type that provides an indication of the nature of alert. It can be one of five values:
    • CONFIRMATION (a hint to confirm user actions)
    • ERROR (a hint to alert the user to an erroneous operation)
    • INFO (provide a information to the user)
    • WARNING (a hint to warn the user of a potentially dangerous operation)
    • ALARM (a hint to alert the user to an event for which the user has previously requested to be notified)

So, the next step is to add a data member of type Alert to your MIDlet class.

public class UserRegistration extends MIDlet implements CommandListener {
    //...
    private Alert messageAlert;
    //...
} 

Then, you will create an instance of the Alert class and passing the title of your alert to that class, which will be "Registration Complete". 

public UserRegistration() {
    //...
    messageAlert = new Alert("Registration Complete");
}

As the alert will be displayed for a certain period of time, you will now specify this period in milliseconds using the setTimeout() method and the type of alert which will be CONFIRMATION.

public UserRegistration() {
    //...
    messageAlert.setTimeout(5000);
    messageAlert.setType(AlertType.CONFIRMATION);
} 

Read TextField Contents

You can read the text field content entered by the user at any time using the TextField getString() method and you can also change it using setString() method, but first you will handle the command action for the OK and Exit commands.

public void commandAction(Command c, Displayable d) {
    if (d == registrationFrm) {
        if (c == okCmd) {
            //Show Message command action
        }
        //Exit command action
        //...
    }
} 

The next step is you will build a simple thanks message after reading the name from the name text field using the getString() method.

if (c == okCmd) {
    String messageContent;
    messageContent = "Thanks " + nameTxt.getString() + "\nRegistration Complete.";
} 

Display Alert and The Contents

Each displayable can be displayed using the Display object setCurrent() method, but this time you need to pass the next displayable parameter to this method. As the alert will timeout after a period of the time, the next displayable will be displayed directly after that.

The final step will be to set the alert text using the setString() and display it using the setCurrent() method with the registration form as the next displayable.

if (c == okCmd) {
    //...
    messageAlert.setString(messageContent);

    display.setCurrent(messageAlert, registrationFrm);
} 

Conclusion

In this article, you learn how to user J2ME to accept input from the user using the text field item, and how J2ME uses different input constraints as a simple data validation. You also learned how to user the notification alert to alert the user about specific events in your application like alarms, errors, warnings, and other types of messages for a specific period of time.

Following is the complete application code, downloadable .java file and the final application result as a .jar file. 

Do not forget to share the article and leave a comment if you have any questions.

import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;

public class UserRegistrationMIDlet extends MIDlet implements CommandListener {
    private Display display;
    private Form registrationFrm;

    private Alert messageAlert;

    private TextField emailTxt;
    private TextField passwordTxt;
    private TextField nameTxt;
    private TextField mobileTxt;
    private TextField urlTxt;

    private Command okCmd;
    private Command exitCmd;

    public UserRegistrationMIDlet() {
        emailTxt = new TextField("Email:", "", 100, TextField.EMAILADDR);
        passwordTxt = new TextField("Password:", "", 16, TextField.PASSWORD);
        nameTxt = new TextField("Name:", "", 50, TextField.ANY);
        mobileTxt = new TextField("Mobile:", "", 15, TextField.PHONENUMBER);
        urlTxt = new TextField("Website:", "", 100, TextField.URL);

        registrationFrm = new Form("User Registration", 
		new Item[] {emailTxt, passwordTxt, nameTxt, mobileTxt, urlTxt});

        messageAlert = new Alert("Registration Complete");
        messageAlert.setTimeout(5000);
        messageAlert.setType(AlertType.CONFIRMATION);

        okCmd = new Command("OK", Command.OK, 0);
        exitCmd = new Command("Exit", Command.EXIT, 1);

        registrationFrm.addCommand(okCmd);
        registrationFrm.addCommand(exitCmd);

        registrationFrm.setCommandListener(this);
    }

    protected void startApp() {
        display = Display.getDisplay(this);
        display.setCurrent(registrationFrm);
    }

    public void commandAction(Command c, Displayable d) {
        if (d == registrationFrm) {
            if (c == okCmd) {
                String messageContent;
                messageContent = "Thanks " + nameTxt.getString() + 
					"\nRegistration Complete.";

                messageAlert.setString(messageContent);

                display.setCurrent(messageAlert, registrationFrm);
            } else if (c == exitCmd) {
                notifyDestroyed();
            }
        }
    }

    protected void pauseApp() {
    }

    protected void destroyApp(boolean unconditional) {
    }
}

History

  • 12th May, 2011: Initial post

License

This article, along with any associated source code and files, is licensed under The Creative Commons Attribution-Share Alike 3.0 Unported License

Share

About the Author

Fadi Hania
Software Developer (Senior) Wateen Technologies
Palestinian Territory (Occupied) Palestinian Territory (Occupied)
A professional developer with a B.Sc. in Computer Engineering. Developing Web, Moblie and Desktop applications and interested in reading and blogging. A cofounder of Wateen Technologies an application development and hosting company.
Visit Fadi Hania Blog to read articles written by Fadi Hania, follow Fadi Hania at Twitter and become a friend with Fadi Hania on Facebook
Follow on   Twitter

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Mobile
Web04 | 2.8.140827.1 | Last Updated 12 May 2011
Article Copyright 2011 by Fadi Hania
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid