recordtest.java

来自「书中的例题」· Java 代码 · 共 244 行

JAVA
244
字号
/***************************************************
*  程序文件名称: RecordTest.java
*  功能:实现对数据记录的添加、删除、浏览等操作。
***************************************************/
import javax.microedition.rms.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
import javax.microedition.io.*;
import java.util.Enumeration;
import java.util.Date;
import java.util.Calendar;
import java.io.*;
public class RecordTest extends MIDlet implements CommandListener 
{
    Display display = null;
    List menu = null; 
    List choose = null;
    Form form = new Form("还贷详细资料");
    Alert alert = new Alert("信息", "成功清除记录...",null, AlertType.INFO);
    static final Command backCommand = new Command("返回", Command.BACK,0);
    static final Command mainMenuCommand = new Command("Main", Command.SCREEN,1);
    static final Command saveCommand = new Command("保存", Command.OK,2);
    static final Command exitCommand = new Command("退出", Command.STOP,3);
    String currentMenu = null;
    RecordStore rs = null;
    DateField loanDate = new DateField("还贷日期", DateField.DATE);
    TextField loanNumber = new TextField("贷款金额", null, 50, TextField.ANY);
    TextField loanAmount = new TextField("还贷金额", null, 20, TextField.NUMERIC);

     // 打开数据库
    public RecordStore openRS(String fileName) 
     {
       try{
            //打开fileName记录存储,第二个参数true代表如果记录存储不存在的话就创建新的记录存储
            //如果为false值则引发RecordStoreNotFoundException异常
            rs = RecordStore.openRecordStore(fileName, true);
          }       
       catch(RecordStoreException rse)   { rse.printStackTrace(); }
       return rs;
     }
     // 添加记录
     //各个记录由字节数组表示,所以加入记录就意味着:加入字节数组到记录存储
     //synchronized代表同步,即同一时刻,保证只有一个线程对RecordStore进行操作
   public synchronized void addNewLoan(String record) 
     {
       ByteArrayOutputStream baos = new ByteArrayOutputStream();
       DataOutputStream daos = new DataOutputStream(baos);
       try { daos.writeUTF(record);}
       catch (IOException ioe) 
         {
          System.out.println(ioe);
          ioe.printStackTrace();
         }
       byte[] bytearr = baos.toByteArray();
       try{
            //加入记录到记录存储,该方法有三个参数,第一个是要加入的字节数组
            //第二个是字节数组内的offset(位移),第三个指要加入的字节数目
            rs.addRecord(bytearr, 0, bytearr.length);
          }
       catch (RecordStoreException rse) 
          {
           System.out.println(rse);
           rse.printStackTrace();
          }
      }
   
	//删除记录
    public void deleteRS() 
    {
     try{
          RecordEnumeration re = enumerate();
          while(re.hasNextElement()) 
             {
               int id = re.nextRecordId();              
                rs.deleteRecord(id);
              }
          showAlert();       
         } 
      catch (Exception e) { }
    }

	//浏览记录
public synchronized RecordEnumeration enumerate()
throws RecordStoreNotOpenException 
  {
    return rs.enumerateRecords(null, null, false);
  }
   
//关闭数据库
public void closeRS()
throws RecordStoreNotOpenException, RecordStoreException 
 {
   //检索记录存储中的记录总数,如果记录存储是空的则删除这个记录存储
   if (rs.getNumRecords() == 0) 
     {
       String fileName = rs.getName();
       rs.closeRecordStore();
       rs.deleteRecordStore(fileName);
     } 
   else 
     { rs.closeRecordStore(); }
 }

 
 public void startApp() throws MIDletStateChangeException 
   {
     display = Display.getDisplay(this);
      // 打开记录存储,没有的话就创建新的
     try{  openRS("myloan");         } 
     catch(Exception e) {     }
     menu = new List("Loan data", Choice.IMPLICIT);
     menu.append("添加记录 ", null);
     menu.append("显示记录 ", null); 
     menu.append("删除全部条目", null); 
     menu.addCommand(exitCommand);
     menu.setCommandListener(this);
     form.append(loanNumber);
     form.append(loanDate);
     form.append(loanAmount);
     mainMenu();
   }

public void pauseApp() 
  {
    display = null;
    choose = null;
    menu = null;
    form = null;       
    try{ closeRS(); } 
    catch(Exception e) {}
  }
 
 public void destroyApp(boolean unconditional) 
  {
    try{closeRS();} 
    catch(Exception e) {}
    notifyDestroyed();
  }
 void mainMenu() 
  {
    display.setCurrent(menu);
    currentMenu = "Main"; 
  }

public void showAlert()
 {
  try 
    {
      alert.setTimeout(Alert.FOREVER);
      display.setCurrent(alert);
    }
  catch(Exception e) {}
 }
 
 // 日期格式转换: mm/dd/yyyy日期转换为String类型
 public String dateTostr(Date dateVal) 
  {
    Calendar calendar = Calendar.getInstance();         
    calendar.setTime(dateVal);                            
    String strDate = Integer.toString (calendar.get(calendar.DAY_OF_MONTH));
    String strMonth = Integer.toString (calendar.get(calendar.MONTH)+1);                     String strYear = Integer.toString (calendar.get(calendar.YEAR));
    return  strMonth + "/" + strDate + "/" + strYear; 
  }

    // Show the form
 public void addLoan () 
  {
   form.addCommand(saveCommand);
   form.addCommand(backCommand);
   form.setCommandListener(this);
   display.setCurrent(form);
   currentMenu = "Add";
  }

    //列出还贷记录信息
  public void listItems() 
   {
     choose = new List("Repayment List", Choice.IMPLICIT);
     choose.addCommand(backCommand);
     choose.setCommandListener(this);
     try {
        RecordEnumeration re = enumerate();
        while(re.hasNextElement()) 
          {
            String theList = new String(re.nextRecord());
            choose.append(theList, null);
           }
        } 
     catch(Exception e) {}
     display.setCurrent(choose);
     currentMenu = "List"; 
   }
  
  public void commandAction(Command c, Displayable d) 
   {
     String label = c.getLabel();
     if (label.equals("Exit"))
	  {
        destroyApp(true);
      } 
     else if (label.equals("Save")) 
      {
        if(currentMenu.equals("Add")) 
          {
            // 添加记录
            try{
                String strNumber = loanNumber.getString();
                String strAmount = loanAmount.getString();
                String strDate = dateTostr (loanDate.getDate());
                // 输入记录       
                String strResult = strNumber + " ;" + strAmount + " ;" + strDate;
                 // 添加记录
                addNewLoan(strResult);
              } 
             catch(Exception e) {} 
             mainMenu();
           } 
       }
      else if (label.equals("Back")) 
       {
        if(currentMenu.equals("List")) 
         {
           mainMenu();
         }
        else if(currentMenu.equals("Add")) 
         {
           mainMenu();
         }
       }
      else 
        {
          List down = (List)display.getCurrent();
          switch(down.getSelectedIndex()) 
            {
             case 0: addLoan();break;
             case 1:  listItems();break;
             case 2:  deleteRS();break;
            }
        }
   }
}


⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?