Tuesday, May 4, 2010

J2ME - Form - Adding Items to Form

J2ME Forms can show different controls. For example you can show different labels, text fields for data entry, choice boxes and so on. We will address these fields in detail in our later posts but today lets see how to add simple fields to J2ME Form.

Following code will run and show a Form on your phone screen that will show three different items. First item is a plan String. Second item is a StringItem which is different from plain text string in a way that it has a title and a body. Different phones show different output for StringItem. The third Item added to the phone screen is a TextField. TextField is used for data entry. It has a label and a related data input box where you can type in information. Following is the code for the program:

        Form f = new Form("Form Title");

        StringItem label = new StringItem("User ID", "119");
        TextField login = new TextField("Login", "", 30, TextField.ANY);

        f.append("This is a simple string");
        f.append(label);
        f.append(login);
  
        display.setCurrent(f);


First line instantiates the Form and the only argument will work as the title of the Form. Second line instantiates a StringItem that will show a labeled String on the Form. Two arguments to the StringItem variable are label and string itself respectively. Third line is instantiating the TextField that will show a labeled text input box. You can type into this box for giving inputs. Argument to the TextField is the label of the box, second argument is the default text, if any (blank in our code's case) , third argument is the maximum number of characters allowed to be typed into this box and the last argument TextField.ANY is the input constraint. We will talk about TextField constrains later, for now you can type ANY text here.

Last four lines are simply calling append() method, that will add things to the form and showing the Form onto the phone screen. Following is the output of the program:


Following is the code for the whole program:

 package hello;

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

public class HelloMIDlet extends MIDlet implements CommandListener {

    private Command exitCommand; // The exit command
    private Display display;     // The display for this MIDlet

    public HelloMIDlet() {
        display = Display.getDisplay(this);
        exitCommand = new Command("Exit", Command.EXIT, 0);
    }

    public void startApp() {
        Form f = new Form("Form Title");

        f.addCommand(exitCommand);
        f.setCommandListener(this);

        StringItem label = new StringItem("User ID", "119");
        TextField login = new TextField("Login", "", 30, TextField.ANY);


        f.append("This is a simple string");
        f.append(label);
        f.append(login);
       

        display.setCurrent(f);
    }

    public void pauseApp() {
    }

    public void destroyApp(boolean unconditional) {
    }

    public void commandAction(Command c, Displayable s) {
        if (c == exitCommand) {
            destroyApp(false);
            notifyDestroyed();
        }
    }

}









Thursday, March 18, 2010

J2ME - Alert Types - Code example

As discussed in J2ME Alerts example earlier, we can show message boxes to the J2ME application users by using Alerts. You can show text alerts as well as Image alerts. Alerts have different types. Each type of alert has a different icon that visually represents the message being given by the Alert.

Each section blow gives a code chunk that shows a different type of Alert in a J2ME app.

AlertType Alarm

This type of Alert shows an alarm typically based on a pre-defined time when  user needs to be reminded of something. If your program is reminding the user of some time based event, this is the alert to use. The code used for this type of alert is :

            Alert a = new Alert("This is the alert");
            a.setTitle("Alert");
            a.setType(AlertType.ALARM);
            a.setTimeout(Alert.FOREVER);
            display.setCurrent(a);

And the output will look something like:



AlertType CONFIRMATION
This type of alert is used to confirm something from the user. If you are inquiring or questionging the user in a message, this is the AlertType to be used.

Here's the code to show such an Alert:

            Alert a = new Alert("This is the alert");
            a.setTitle("Alert");
            a.setType(AlertType.CONFIRMATION);
            a.setTimeout(Alert.FOREVER);
            display.setCurrent(a);

 The output of the code will be similar to the image below:



AlertType ERROR
When you want to communicate about an error that has occured in a J2ME program, use AlertType.ERROR in your code. Here's the code sample:

            Alert a = new Alert("This is the alert");
            a.setTitle("Alert");
            a.setType(AlertType.ERROR);
            a.setTimeout(Alert.FOREVER);
            display.setCurrent(a);

The output of the above code is shown in the screenshot below:



AlertType INFO
An error that gives some general information to the user, you should use INFO type alert. This can be done by using AlertType.INFO when instantiating the Alert object in your code. Following code is used to show an INFO type alert:

            Alert a = new Alert("This is the alert");
            a.setTitle("Alert");
            a.setType(AlertType.INFO);
            a.setTimeout(Alert.FOREVER);
            display.setCurrent(a);

And here is the output screenshot of the output of the above code.



AlertType Alarm
As the name suggests, this kind of Alert is used to give warnings to the user in a J2ME app. Use following code for giving such warnings:

            Alert a = new Alert("This is the alert");
            a.setTitle("Alert");
            a.setType(AlertType.WARNING);
            a.setTimeout(Alert.FOREVER);
            display.setCurrent(a);

 The output of the above code is given below:




Please note that above alert types are given standard alert types defined in J2ME. Any phones supporting J2ME MIDP should have these alerts available on device. The type of icon, size, shape and color of the icons on the Alert may be different depending on the implementation of the J2ME alerts on that device, but the basic reason of showing the alerts and the type of icons shown on all devices will give out the same message to the user.


Related J2ME articles:

 

J2ME - Alert - How to show images in alerts

We already saw a code example that shows text based Alerts in J2ME. Alert is a way of showing user targeted alert messages in J2ME. You can also add an image or icon to this alert to make it more attractive and more explanatory. This is important to show images in alerts to associate an automatic sense of users to a typical type of message. If alert shows an error and you show a red icon with the Alert, you will automatically pass half the message to the user even before the user reads the message.

Also, for applications that are used in different parts of the world by people from different languages and cultures, images and icons can convey the message better than words.

Here is the code that will show an Alert with an Image included.

Image i = Image.createImage("/cube.png");
Alert a = new Alert("Alert!",  "This is the alert!", i, AlertType.INFO );
a.setTimeout(Alert.FOREVER);
display.setCurrent(a);


A few pointers to elaborate above code. Image is obviously the class that represents images in J2ME. Image is part of javax.microedition.lcdui package. createImage() is a static method of Image class that will load the image file from the MIDlet package.

We will discuss this later in detail but MIDlet applications, when ready for deployment, are compressed in .jar files and .jar files retain the hierarchy of files and folders within the .jar file. In our example, the code is picking a png file named cube.png from /  , the root directory in the jar.

Once the image is loaded, it is passed as an argument of the Alert constructor. There are four arguments. Argument 1 is the title of the Alert, argument 2 is the body text of the alert, argument 3 is the image and last argument is Alert type. We will have more discussion later on the alert types.

Here's the output of the above code.





A word of caution. When loading an image from the file, you must catch IOException that is thrown by Image.createImage() method. You can either catch the exception to show an error message or can throw it in the method's definition where you load this image.


Related J2ME Articles

 

    Tuesday, March 16, 2010

    J2ME - Alert - Code Examle

    Alert is a J2ME way of showing messages, errors and prompts on screen. The exact look and feel will be different for each device but the purpose is same for all alerts across different J2ME phones. You can show text or image on the prompt and the error can either remain on the screen for a few seconds or may remain there forever, till the user presses ok and terminates the Alert.

    How to show an Alert

    Here is the code that shows the alert on the screen.

            Alert a = new Alert("This is the alert!");
            a.setTimeout(4000);
            display.setCurrent(a);

    This Alert example will instantiate an Alert with the alert text message. The alert will be shown for 4 seconds (4000 miliseconds) and the last line is actually displaying the alert on the screen. User can hit ok or done while alert is shown to dismis the alert and go back to the screen it came from. By default the time-out is two seconds. So if you do not set the timeout, the alert will be shown for two seconds.

            Alert a = new Alert("This is the alert!");
            display.setCurrent(a);

    If you want the Alert to be visible indefinitely, you can do it by using following piece of code:

            Alert a = new Alert("This is the alert!");
            a.setTimeout(Alert.FOREVER);
            display.setCurrent(a);
           
     This Alert can only be dismissed manually by pressing OK or Dismiss option on your phone. The exact label depends on the implementation on that particular phone.

    How Alert is different
    Alert is different from other types of J2ME screens. It keeps a portion of the previous screen visible and shows the error on top of it.

    Output



    In this tutorial, we displayed how to show a simple Alert using J2ME. Later, we will also cover a few different variants of the Alerts.



    Related Articles

    How to show Images in Alerts
    Different Alert types and their implementation
    J2ME - Form - Code Example


     

    Sunday, March 14, 2010

    J2ME - Form - Code Example

    This example will show you how simple it is to make J2ME Forms. All you have to do is create a MIDlet and in the startApp() method instantiate a Form and show a "Hello" string on top of it. If you have the development environment properly set up, this should take a few moments.

    As you have read in the previous articles about the MIDlet life-cycle, startApp() is the method that is called by the J2ME runtime on the device and you can write your initializing code in this MIDlet method.
     
    Following is a simple code chunk that will show a Form with a String on it.

    How to create a Form in J2ME

    In this code, on line 1 we create an instance of the Form. "Form Title" is obviously the text that will show as the title of the form on the screen. On line 2, we append a string to be shown on the form and the last line is making the Form visible on the screen.

            Form f = new Form("Form Title");
            f.append("Hello - This is the form");
            Display.getDisplay(this).setCurrent(f);


    Here is the full code MIDlet Example


    import javax.microedition.lcdui.Display;
    import javax.microedition.lcdui.Form;
    import javax.microedition.midlet.MIDlet;
    import javax.microedition.midlet.MIDletStateChangeException;

    public class FormExample extends MIDlet {

        protected void startApp() throws MIDletStateChangeException {
            Form f = new Form("Form Title");
            f.append("Hello - This is the form");
            Display.getDisplay(this).setCurrent(f);
        }
       
        public FormExample() {   
        }

        protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
        }

        protected void pauseApp() {
        }
    }




    Output of the above code:







    J2ME Form code example








    Related Articles:



    J2ME - Screen and visual user interfaces

    J2ME provides a variety of methods of showing objects and  controls on screen. You can use typical form like screens that will have text boxes, drop downs and buttons for takeing input from user or you can use custom drawing capable panels called Canvas.

    Following diagram shows a typical hierarchy of the J2ME user interface classes:

    As you can see, every visual element shown on J2ME screens is a sub-class of Displayable. All these classes are found inside javax.microedition.lcdui package or its sub-packages. Displayable hence is also found at javax.microedition.lcdui.Displayable. Screen class is hardly ever used for direct screen display and the most common screen item on J2ME apps is either Form or a Canvas.

    Form is a screen that can display other controls like buttons, text fields and check boxes on top of it. Canvas is a more general drawing  board on which you can create visual interfaces by drawing lines, arcs, text, colors and images.

    At times, there is no need of a full fledged Form and a full-screen TextBox or a List could do the trick as shown in the hierarchy. Alerts are a way of showing infromation or errors to the user. We will study further about these classes in the later articles.

    Related Articles:

    J2ME - Form Example
    J2ME - Canvas Example
    J2ME - List Example
    J2ME - Alert Example
    J2ME - TextBox Example

    Mobile Software Development - User Interfaces

    Mobile devices capable of running J2ME apps, Android apps or BlackBerry apps are usually small , hand held computers that have very limited capabilities as compared to the desktop computers but they do good justice when programmed properly. As a mobile application developer you should take care of the user while developing apps. The biggest challenge is how these devices interact with the user and how they allow the user to interact with them.

    Following are a few typical challenges that are faced by mobile device users in terms of the user interfaces:
    • Small screen and a small area to display objects
    • Small key-board/keypad and in some cases no keypad (tourchscreens).
    • Little or at times no support for audio output
    • Little or not support for audio input
    • Absence of a pointing device like a mouse (on some devices).
    • Very limited or no printing capabilities
    With the passage of time, device manufacturers have been trying to find ways to improve usability by adding more capabilities. Latest touch-screen devices allow you to touch the point of interest and that eliminates the need of any mouse like device. Similarly, latest devices have great audio rendering and capturing capabilities regardless of the fact that these are absolutely micro devices with very small sizes.

    Regardless of these efforts, you as a mobile programmer will have to put constant effort to make the user interfaces easy to use and simple to understand. Here are a few simple guidelines.

    • Never clutter your screen. Show as few objects and elements as you can.
    • If you need to show many objects, data controls or other items, use multiple screen strategy, something like wizards. 
    • Use good navigation options when moving back and forth on such screens.
    • Use sound alerts whenever possible.
    • Use visual indicators instead of text whenever possible. For example use icons to replace error messages to avoid extensive onscreen readings.
    • Take maximum use of the device capabilities to avoid extra typing. For example on GPS devices, never ask the user about his current city.
    • Help user with auto complete and dictionary text options to reduce the number of key presses per word typed.
    • Use different color text for different type of text. For example in an email program, subject is always grey and body is always blue. This avoids the need of extra spacing on screen when separating text controls.
    • Consider using landscape or portrait modes of screen depending on the application.
    • Give visual effects to associate actions. For example a screen transition of swipe right to left always tells that you moved forward one step onto the next screen and a transition from left to right may represent a step back. 
    • Ask many people to use your app to give you feedback on user interface experience and only your users can suggest improvements, not you yourself.
    This list could go on forever. We will try to update the list every now and then. Please do leave your experiences and ideas in the comments box to contribute to this list. At mobile-apps-dev.com, we will try our best to help you make apps that are more usable and user-friendly.

    Related Articles:

    J2ME Screen and visual interfaces
    J2ME Form example
    J2ME Canvas example

    Monday, March 8, 2010

    J2ME - MIDlet lifecycle explained

    MIDlet is the basic execution unit in J2ME and it is in different states in different point of its execution. When you launch an application, operating system loads it up. There are three basic states of a MIDlet:
    1. PAUSED
    2. DESTOYED
    3. ACTIVE
    The names are self explanatory. When the application initially loads, its in the PAUSED state. When application starts execution, it transitions from PAUSED to ACTIVE state but before going to active state, startApp() method of the MIDlet is called which you must implement in your MIDlet class.

    There are several instances where you yourself or the operating system will request your MIDlet to be paused for example in an event of an incoming call. When your application is requested to be paused, it goes from ACTIVE to PAUSED state and before it gets pasued, pauseApp() method is executed. If you want to stop or pause any running threads in your app while it is in paused state, you should write your code in pauseApp() method.

    And whenever you exit your application, it will transition from the ACTIVE or PAUSED state to a DESTROYED state. In destroyed state, all resources are de-allocated and the application process is killed. If you want to run some code at the exit time of your applicatin, like closing network connections and storage devices, you should write your code in destroyApp() method of your MIDlet class.

    Following diagram gives a clear picture of the MIDlet lifecycle in J2ME applications.




    Related Articles:

    What is a MIDlet?
    How to write your first J2ME app?
    Mobile applications - User interfaces
    J2ME - User interfaces

    Sunday, March 7, 2010

    J2ME - What is a MIDlet

    MIDlet in simple words is a mobile application for Java enabled mobile phones. MIDlet is an application that runs on MIDP (Mobile Interface Data Profile) compliant devices. Some times, J2ME apps are alternatively called MIDlets because each executable application starts execution from the MIDlet class.

    To start your application programming on J2ME, your main application class should extend javax.microedition.midlet which is defined in MIDP. We will see in detail, what is a MIDlet lifecycle but right now I'm listing a simple MIDlet applcication that shows a simple Hello World message.


    package hello;

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

    public class HelloMIDlet extends MIDlet implements CommandListener {

        private Command exitCommand; // The exit command
        private Display display;     // The display for this MIDlet

        public HelloMIDlet() {
            display = Display.getDisplay(this);
            exitCommand = new Command("Exit", Command.EXIT, 0);
        }

        public void startApp() {
            TextBox t = new TextBox("Hello", "Hello, World!", 256, 0);

            t.addCommand(exitCommand);
            t.setCommandListener(this);

            display.setCurrent(t);
        }

        public void pauseApp() {
        }

        public void destroyApp(boolean unconditional) {
        }

        public void commandAction(Command c, Displayable s) {
            if (c == exitCommand) {
                destroyApp(false);
                notifyDestroyed();
            }
        }

    }



    If you've been reading the tutorials in sequence, you must have recognized that this is the same code we posted in an earlier post. Read this post to read more about the details of this code and how it works.

    This is important to know that unlike other platforms where java runs, J2ME has not main method to start the application. Its rather the startApp() method of the MIDlet class that is called by the runtime to initiate the execution of the application.

    To read further, please read "What is a MIDlet lifecycle".


    Other related articles:

    J2ME - How to write your first app.
    J2ME - How to set up development environment on Windows
    J2ME - What is a MIDlet life cycle




    Saturday, February 27, 2010

    J2ME - How to write your first app.

    After setting up your development environment, now is the time to write our first app in J2ME. We call it hello-mobile. To write your first app, make sure your development environment has been setup properly. Click here to read "How to ensure your J2ME development environment is setup properly".

    There are quite a few ways of developing your first J2ME application. We will discuss two ways of doing that.
    1. You can either use Eclipse as your development environment
    2. Or you can use Sun's Micro Edition software development kit

    We will mostly use Eclipse for our development tutorials but for the first app, we will demonstrate the both tools. Here we go:

    1. Your first J2ME app using Java Platfrom Micro Edition SDK Tool
    2. Your first J2ME app using Eclipse


    Our tutorials here assume that you have the basic software development knowledge in Java Programming language or have at least acquintance of the language.

    Some books for you to learn Java in case you are not very proficient with Java

    -------------------------------------


    Related Articles

    How to ensure your J2ME Development environment is setup properly

    J2ME - Basic Introduction