Wednesday, 23 January 2013

MIDlet Application For Login in J2ME

Program:

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

public class LogInMidlet extends MIDlet implements CommandListener
{
    private Display d;
    private Form f;

    private StringItem lblUserName, lblPassword;
    private TextField tfUserName, tfPassword;
    private Command cmdOK, cmdCancel, cmdExit;

    public LogInMidlet()
    {
        f = new Form("Login Application");

        lblUserName = new StringItem(null, "User name: ");
        lblPassword = new StringItem(null, "Password: ");

        tfUserName = new TextField("Username: ", "", 10, TextField.ANY);
        tfPassword = new TextField("Password: ", "", 10, TextField.PASSWORD);

        cmdOK = new Command("OK", Command.OK , 2);
        cmdCancel = new Command("Cancel", Command.CANCEL, 2);
        cmdExit = new Command("Exit", Command.EXIT, 1);
    }

    public void startApp()
    {
        d = Display.getDisplay(this);

        f.append(lblUserName);
        f.append(tfUserName);

        f.append(lblPassword);
        f.append(tfPassword);

        f.addCommand(cmdOK);
        f.addCommand(cmdCancel);
        f.addCommand(cmdExit);

        f.setCommandListener(this);

        d.setCurrent(f);
    }

    public void pauseApp() {
    }

    public void destroyApp(boolean unconditional) {
        notifyDestroyed();
    }

    public void commandAction(Command c, Displayable d)
    {
        if(c.equals(cmdExit))
            destroyApp(true);
        else if (c.equals(cmdOK))
            validateUser(tfUserName.getString(), tfPassword.getString());
    }

    public void validateUser(String userName, String pswd)
    {
        if(userName.equals("admin") && pswd.equals("123"))
            welcome();
        else
            tryAgain();
    }

    public void welcome()
    {
        Alert msg = new Alert("Welcome","Login Successful.",  null, AlertType.INFO);

        tfUserName.setString(null);
        tfPassword.setString(null);

        d.setCurrent(msg, f);
    }

    public void tryAgain()
    {
        Alert msg = new Alert("Error","Incorrect username or password.",  null, AlertType.ERROR);

        tfUserName.setString(null);
        tfPassword.setString(null);

        d.setCurrent(msg, f);
    }
}

Output:


Output Snapshot

Do you like this article?