ServiceListScreen.java

/*
 * Copyright © 2012 Nokia Corporation. All rights reserved.
 * Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation. 
 * Oracle and Java are trademarks or registered trademarks of Oracle and/or its
 * affiliates. Other product and company names mentioned herein may be trademarks
 * or trade names of their respective owners. 
 * See LICENSE.TXT for license information.
 */ 
package com.nokia.example.bcexchanger.ui;

import java.util.Enumeration;
import java.util.Vector;

import javax.microedition.lcdui.Choice;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.List;

import com.nokia.example.bcexchanger.*;

/**
 * 
 * This class implements the service list screen. This screen is used
 * to when several services are available in vicinity and allows user
 * to select the desired one. Using this screen user can select the
 * service or cancel the process
 * 
 * The class is extending an example.BCExchanger.ui.Screen class
 * 
 * @see example.BCExchanger.ui.Screen Design patterns: State
 * 
 */
public class ServiceListScreen extends Screen {

    private List list;
    private Command okCommand;
    private Command cancelCommand;

    /**
     * Constructor
     * 
     * @param _midlet -
     *          the parent class which keeps the current UI state
     * @param friendlyNames -
     *          vector of the friendly names of the devices which
     *          contain the services
     */
    public ServiceListScreen(BCExchangerMIDlet _midlet,
            Vector friendlyNames) {
        super(_midlet);

        list = new List("Choose service", Choice.EXCLUSIVE);

        if (friendlyNames.isEmpty()) {
            // list should not be empty
            throw new RuntimeException("Internal error #23");
        }

        Enumeration e = friendlyNames.elements();

        while (e.hasMoreElements()) {
            list.append((String) e.nextElement(), null);
        }

        okCommand = new Command("Ok", Command.OK, 1);
        cancelCommand = new Command("Cancel", Command.CANCEL, 1);

        list.addCommand(okCommand);
        list.addCommand(cancelCommand);

        list.setCommandListener(this);

        displayable = list;
    }

    public void commandAction(Command command, Displayable _displayable) {
        if (_displayable != list) {
            // wrong displayable
            throw new RuntimeException("Internal error #24");
        }

        if (command == okCommand) {
            midlet.serviceSelected(list.getSelectedIndex());
            midlet.unblock();
        } else if (command == cancelCommand) {
            midlet.getExchanger().cancelSending();
            midlet.unblock();
        } else {
            // unknown command
            throw new RuntimeException("Internal error #25");
        }

    }
}