Implementing the handlers

ChoiceBean class

ChoiceBean is a simple bean class used for managing the choice list presented to the user when the MIDlet starts.

package com.nokia.midp.example.jsr211.texthandler;

import javax.microedition.lcdui.StringItem;

public class ChoiceBean {
	
	/** Choice Key also used as a choice title*/
	private StringItem keyTitle;
	
	/** Contains item URL*/
	private String choiceName;
	
	ChoiceBean(StringItem _keyTitle, String _choiceName){
		keyTitle = _keyTitle;
		choiceName =_choiceName;
	}

	public StringItem getKeyTitle() {
		return keyTitle;
	}

	public void setKeyTitle(StringItem keyTitle) {
		this.keyTitle = keyTitle;
	}

	public String getChoiceName() {
		return choiceName;
	}

	public void setChoiceName(String choiceName) {
		this.choiceName = choiceName;
	}
}

ChoiceList class

This class creates the main menu List, which contains the choices for the user. The content for the List is read from the JAD file or the resource file. In this example, the JAD file contains a Nok-Resource-File-Name attribute, which is defined in the code below. As its value, this attribute has a plaintext file in the res directory, which in turn contains further links for downloadable content. There are also basic methods for adding/deleting items from the List in the MIDlet.

For direct links from the JAD file to the content, there is an option to use the Nok-Choice- attribute. Both of these follow the same naming convention: <name displayed to the user> <separator ~><link to the content>

  • Example: Image logo.png~http://localhost/chapi/content/icons/logo.png

  1. Create the ChoiceList class file.

  2. Import the required classes and assign this class to the com.nokia.midp.example.jsr211.texthandler package.

    package com.nokia.midp.example.jsr211.texthandler;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.util.Vector;
    
    import javax.microedition.lcdui.Alert;
    import javax.microedition.lcdui.AlertType;
    import javax.microedition.lcdui.Command;
    import javax.microedition.lcdui.CommandListener;
    import javax.microedition.lcdui.Display;
    import javax.microedition.lcdui.Displayable;
    import javax.microedition.lcdui.Form;
    import javax.microedition.lcdui.Item;
    import javax.microedition.lcdui.ItemCommandListener;
    import javax.microedition.lcdui.StringItem;
    import javax.microedition.lcdui.TextField;
    
  3. Create the main class and the objects to be used in this application. Note the Nok-Choice- and Nok-Resource-File-Name custom JAD attributes.

    public class ChoiceList extends Form implements CommandListener,
    		ItemCommandListener {
    
    	/** Message saying.. fail to load text invocation. */
    	private static final String MSG_FAILED_TO_LOAD_TEXT = "Failed to load text";
    
    	/** Message saying.. Invalid file*/
    	private static final String MSG_INVALID_FILE = "Invalid file";
    
    	/** URL Choice from JAD*/
    	private static final String JAD_NOKIA_CHOICE = "Nok-Choice-";
    
    	/** Resource file name from JAD*/
    	private static final String JAD_NOKIA_RESOURCE_FILE = "Nok-Resource-File-Name";
    
    	/** New line separator*/
    	private static final String NEW_LINE = "\r\n";
    
    	/** Key value separator for link.txt file. */
    	private static final String SEPARATOR = "~";
    
    	/** Display instance. */
    	private Display display = null;
    
    	/** List of choices */
    	private Vector choiceList = new Vector();
    
    	/** Alert to display choice details*/
    	Alert alert = new Alert("Choice Details");
    
    	/** TextField to enter Title of the choice */
    	private TextField titleTextField;
    
    	/** TextField to enter choice URL. */
    	private TextField urlTextField;
    
    	/** Command to execute the choice */
    	private Command fireCommand = new Command("Execute", Command.ITEM, 1);
    
    	/** Command to add item to the list. */
    	private Command addCommand = new Command("Add", Command.ITEM, 2);
    
    	/** Command to Delete Choice from the list. */
    	private Command deleteCommand = new Command("Delete", Command.ITEM, 3);
    
    	/** Command to view details of the choice */
    	private Command detailCommand = new Command("Details", Command.ITEM, 4);
    
    	/** Command to save item to the list. */
    	private Command saveCommand = new Command("Save", Command.ITEM, 1);
    
    	/** Command to exit from the application */
    	private Command exitCommand = new Command("Exit", Command.ITEM, 5);
    
    	/** The ItemCommandListener that gets notified of select events. */
    	private TextHandler textHandler;
    
  4. Create a constructor for the list of choices using an instance of TextHandler class.

    	/**
    	 * @param title Choice list title.
    	 * @param _textHandler Instance of TextHandler class to handle UI part.
    	 */
    	public ChoiceList(String title, TextHandler _textHandler) {
    		super(title);
    
    		textHandler = _textHandler;
    		display = _textHandler.display;
    
    		// Read favorites links form the resource file
    		String strChoices = null;
    
    		try {
    			strChoices = readResourceFile();
    
    		} catch (IOException ex) {
    			choiceList.removeAllElements();
    			choiceList.addElement(ChoiceList.MSG_INVALID_FILE);
    		}
    
    		try {
    			generateChoiceList(strChoices);
    		} catch (Exception e) {
    			// Failed to load resources
    			choiceList.removeAllElements();
    			choiceList.addElement(ChoiceList.MSG_FAILED_TO_LOAD_TEXT);
    		}
    
    		displayChoices();
    
    		configureTextFields();
    	}
    
  5. Create two TextFields for the content.

    	/**
    	 * TextField configuration
    	 */
    	private void configureTextFields() {
    		titleTextField = new TextField("Add Title:", "", 30,
    				TextField.INITIAL_CAPS_WORD);
    		titleTextField.setLayout(Item.LAYOUT_DEFAULT
    				| Item.LAYOUT_NEWLINE_AFTER);
    		titleTextField.addCommand(saveCommand);
    		titleTextField.setItemCommandListener(this);
    		urlTextField = new TextField("Add Link:", "http://", 128, TextField.URL);
    		urlTextField.setLayout(Item.LAYOUT_DEFAULT | Item.LAYOUT_NEWLINE_AFTER);
    		urlTextField.addCommand(saveCommand);
    		urlTextField.setItemCommandListener(this);
    
    	}
    
  6. Display the choices. The content for this is read from the ChoiceBean class

    private void displayChoices() {
    
    		for (int index = 0; index < choiceList.size(); index++) {
    
    			ChoiceBean choiceBean = (ChoiceBean) choiceList.elementAt(index);
    			this.append(choiceBean.getKeyTitle());
    		}
    
    		addCommand(exitCommand);
    		setCommandListener(this);
    	}
    
  7. Create a method for generating the list of choices

    private void generateChoiceList(String strChoices) {
    
    		while ((strChoices != null)
    				&& (strChoices.indexOf(ChoiceList.NEW_LINE) != -1)) {
    
    			String item = strChoices.substring(0, strChoices
    					.indexOf(ChoiceList.NEW_LINE));
    
    			String key = item.substring(0, item.indexOf(ChoiceList.SEPARATOR));
    			String value = item.substring(item.indexOf(ChoiceList.SEPARATOR) + 1);
    
    			addChoice(key,value)
    
    			strChoices = strChoices.substring(strChoices
    					.indexOf(ChoiceList.NEW_LINE) + 2);
    		}
    
  8. Check if JAD_NOKIA_CHOICE (Nok-Choice-#) attributes are set in the JAD file. If they are are found, enter them as values to the list of choices.

    	// Read from jad file, if entry exists
    		int keyNum = 1;
    		strChoices = null;
    		do {
    			strChoices = textHandler.getAppProperty(ChoiceList.JAD_NOKIA_CHOICE
    					+ keyNum++);
    			if (strChoices == null)
    				return;
    
    			String key = "";
    			String value = "";
    			if (strChoices.indexOf(ChoiceList.SEPARATOR) != -1) {
    				key = strChoices.substring(0, strChoices
    						.indexOf(ChoiceList.SEPARATOR));
    				value = strChoices.substring(strChoices
    						.indexOf(ChoiceList.SEPARATOR) + 1);
    
    				if (value != null) {
    					addChoice(key,value)
    				}
    
    			}
    
    		} while (strChoices != null);
    	}
    
  9. Read the data from the resource file and enter it into a String.

    	/**
    	 * @return string generated after reading the data from the resource file
    	 * @throws IOException
    	 */
    	private String readResourceFile() throws IOException {
    		InputStream is = getClass().getResourceAsStream(
    				textHandler.getAppProperty(JAD_NOKIA_RESOURCE_FILE));
    		InputStreamReader r = new InputStreamReader(is);
    
    		char[] buffer = new char[32];
    		StringBuffer sb = new StringBuffer();
    		int count;
    
    		while ((count = r.read(buffer, 0, buffer.length)) > -1) {
    			sb.append(buffer, 0, count);
    		}
    
    		return sb.toString();
    	}
    
  10. Create Commands for adding and deleting actions in the list.

    	/**
    	 * @param keyTitle title of the new choice
    	 * @param choiceName URL of the given choice
    	 */
    	public void addChoice(String keyTitle, String choiceName) {
    
    		StringItem choice = new StringItem(null, keyTitle, Item.HYPERLINK);
    		choice.setLayout(Item.LAYOUT_2 | Item.LAYOUT_NEWLINE_AFTER);
    		choice.setDefaultCommand(fireCommand);
    		choice.addCommand(addCommand);
    		choice.addCommand(deleteCommand);
    		choice.addCommand(detailCommand);
    		choice.setItemCommandListener(this);
    
    		ChoiceBean choiceBean = new ChoiceBean(choice, choiceName);
    		choiceList.addElement(choiceBean);
    
    	}
    
    	/**
    	 * Delete choice from the current list
    	 * 
    	 * @param index delete choice based on the given index.
    	 */
    	public void deleteChoice(int index) {
    		choiceList.removeElementAt(index);
    	}
    
  11. Add the Command handling functions.

    	/**
    	 * Handles item specific command
    	 */
    	public void commandAction(Command command, Item item) {
    
    		int itemIndex = getItemIndex(item);
    
    		if (command == fireCommand) {
    
    			if (textHandler != null) {
    
    				String url = getURL(item);
    
    				if (url == null) {
    					url = ((StringItem) item).getText();
    				}
    			}
    		} else if (command == addCommand) {
    
    			// Delete entire list from the form.
    			removeItems();
    
    			// Reset strings
    			titleTextField.setString("");
    			urlTextField.setString("http://");
    
    			// Add text fields to add new choice
    			this.insert(0, titleTextField);
    			this.insert(1, urlTextField);
    
    		} else if (command == deleteCommand) {
    
    			this.delete(itemIndex);
    			choiceList.removeElementAt(itemIndex);
    
    		} else if (command == detailCommand) {
    
    			alert.setString(((ChoiceBean) choiceList.elementAt(itemIndex))
    					.getChoiceName());
    			alert.setTimeout(Alert.FOREVER);
    			alert.setType(AlertType.INFO);
    			display.setCurrent(alert);
    
    		} else if (command == saveCommand) {
    
    			addChoice(titleTextField.getString().trim(), urlTextField
    					.getString().trim());
    
    			// Delete TextFields from the list
    			removeItems();
    
    			displayChoices();
    		}
    
    	}
    

    Add more Commands for the confirmation dialog and for exiting the MIDlet.

    	private void removeItems() {
    		while (this.size() > 0) {
    			this.delete(0);
    		}
    	}
    
    	public void commandAction(Command command, Displayable disp) {
    		if (command == exitCommand) {
    			textHandler.destroyApp(true);
    		}
    	}
    
  12. Create a method for finding the index of the Item in the Form.

    	/**
    	 * @param item to find the index of
    	 * @return the index of the item or -1 if not found.
    	 */
    	private int getItemIndex(Item item) {
    		int itemIndex = 0;
    
    		for (itemIndex = 0; itemIndex < this.size(); itemIndex++) {
    			if (this.get(itemIndex) == item) {
    				return itemIndex;
    			}
    		}
    
    		return -1;
    	}
    
  13. Create a method for retrieving the URL associated with the selected Form Item.

    	/**
    	 * @param item for which to get the URL
    	 * @return the URL at index
    	 */
    	public String getURL(Item item) {
    		int index = getItemIndex(item);
    
    		return (index < 0) ? null : ((ChoiceBean) choiceList.elementAt(index))
    				.getChoiceName();
    	}
    }