import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.rms.*;

public class Storage1 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 Storage1()
  {
     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(cmSave);
     text.addCommand(cmRetrieve);
  }
  public void startApp()
  {
     text.setCommandListener(this);
     display.setCurrent(text);
     try{
       rs = RecordStore.openRecordStore("DB1", true);
     }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 == cmSave)
     {
       try{
          String str = text.getString();
          byte[] record = str.getBytes();
          rs.addRecord(record, 0, str.length());
       }catch(Exception e){
         System.err.println("** Error: addRecord(): " + e.getMessage());
       }
     }
     else if (c == cmRetrieve)
     {
       try{
          byte[] data;
          data = rs.getRecord(n);
          String record = new String(data);
          text.setString(record);
          n++;
       }catch(Exception e){
          System.err.println("** Error: getRecord(): " + e.getMessage());
       }
    }
     else if (c == cmExit)
     {
        try{
           rs.closeRecordStore();
        }catch(Exception e){
           System.err.println("** Error: closeRecordStore(): " + e.getMessage());
        }
        destroyApp(false);
        notifyDestroyed();
     }
  }
}


