import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.rms.*;

public class Storage2 extends MIDlet implements CommandListener
{
  private Display display;
  private TextBox text;
  private Command cmSave;
  private Command cmRetrieve;
  private Command cmExit;
  private int n = 1;

  private RecordStore rs;

  public Storage2()
  {
     display = Display.getDisplay(this);
     cmSave = new Command("Save", Command.SCREEN, 1);
     cmRetrieve = new Command("Retrieve", Command.SCREEN, 1);
     cmExit = new Command("Exit", Command.EXIT, 1);
     text = new TextBox("Text", "", 44, TextField.ANY);
     text.addCommand(cmExit);
     text.addCommand(cmRetrieve);
 }
  public void startApp()
  {
     text.setCommandListener(this);
     display.setCurrent(text);
     try{
        rs = RecordStore.openRecordStore("DB1", false);
     }catch(Exception e){
        System.err.println("** Error: openRecordStore(): " + e.getMessage());
    }

  }
  public void pauseApp()
  { }
  public void destroyApp(boolean unconditional)
  { }
  public void commandAction(Command c, Displayable s)
  {
     if (c == cmRetrieve)
     {
       try{
          byte[] data;
          data = rs.getRecord(n);
          String record = new String(data);
          text.setString(n + ". " + record);
          n++;
       }catch(InvalidRecordIDException e){
          text.setString("** no record **");
       }catch(Exception e){
          System.err.println("** Error: getRecord(): " + e.getMessage());
       }

     }
     else if (c == cmExit)
     {
       try{
          rs.closeRecordStore();
          RecordStore.deleteRecordStore("DB1");
       }catch(Exception e){
          System.err.println("** Error: deleteRecordStore(): " + e.getMessage());
       }
       destroyApp(false);
       notifyDestroyed();
     }
  }
}


