站内搜索: 请输入搜索关键词

当前页面: 开发资料首页J2ME 专题J2ME学习笔记(八)-----处理MIDP RMS

J2ME学习笔记(八)-----处理MIDP RMS

摘要: J2ME学习笔记(八)-----处理MIDP RMS

处理MIDP RMS<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

1. RMS(记录管理系统)------借助移动设备中记录存储使数据持久存储。

2. 记录存储-----是由各个记录组成的二进制文件。

3. 记录(存储单位)-----每个记录是一个字节数组。

4. RMS创建记录存储,并把各个记录加入到记录存储中。在加入记录时,对每个记录分配一个唯一的标示符(记录ID)。RMS通过记录ID来管理记录存储中的各个记录。(RMS对记录的实际内容并不关心)。记录ID一直保存到该记录被从记录存储中删除为止。

5. 记录存储----保存在X:\WTK104\appdb目录下,带.db后缀。

6. 实现RMS的包是javax.microedition.rms包。

7. RMS包中只有一个RecordStore类。

8. RecordStore类的几个重要方法:

1) openRecordStore()-----打开记录存储

2) closeRecordStore()-----关闭记录存储

3) deleteRecordStore()-----删除记录存储

4) enumerateRecords()-----记录存储中记录的整个集合

5) getName()-----得到记录存储名

6) getNumRecords()-----记录存储中记录个数

7) addRecord()-----加入记录

8) getRecord()-----检索记录

9) deleteRecord()-----删除记录

9. RMS实例

1) 任务陈述:SaveMyMoney银行应用需要在移动设备上实现数据存储。移动用户向银行贷款之后,首先需要在自己的移动设备上添加该条贷款记录并可以保存,做为备忘录。记录内容包括贷款编号,还贷日期,还贷数目。

2) 步骤1:打开记录存储

RecordStore rs = null;

// Open a record store with the given name(打开记录存储)

public RecordStore openRS(String fileName) {

try

{

//打开fileName记录存储,第二个参数true代表如果记录存储不存在//的话就创建新的记录存储

//如果为false值则引发RecordStoreNotFoundException异常

rs = RecordStore.openRecordStore(fileName, true);

}

catch(RecordStoreException rse)

{

rse.printStackTrace();

}

return rs;

}

3) 步骤2:加入记录到记录存储

// Add a new record (loan) to the record store

//各个记录由字节数组表示,所以加入记录就意味着:加入字节数组到记录存储

//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();

}

}

4) 步骤3:删除记录存储

// Use the enumeration object to delete each record in the record

//store删除记录存储

public void deleteRS()

{

try

{

RecordEnumeration re = enumerate();

while(re.hasNextElement())

{

int id = re.nextRecordId();

rs.deleteRecord(id);

}

showAlert();

}

catch (Exception e) { }

}

5) 步骤4:关闭记录存储

// Close the record store

public void closeRS() throws RecordStoreNotOpenException, RecordStoreException

{

//检索记录存储中的记录总数,如果记录存储是空的则删除这个记录存储

if (rs.getNumRecords() == 0)

{

String fileName = rs.getName();

rs.closeRecordStore();

rs.deleteRecordStore(fileName);

}

else

{

rs.closeRecordStore();

}

}

6) 步骤5:导航记录存储中的记录

// Get the enumeration object.

public synchronized RecordEnumeration enumerate()

throws RecordStoreNotOpenException

{

return rs.enumerateRecords(null, null, false);

}

7) 重要的代码都在写在了上面,下面是所有的代码:

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 LoanMIDlet extends MIDlet implements CommandListener

{

Display display = null;

List menu = null; // The initial menu

List choose = null;

Form form = new Form("Repayment Details");

//Define the Alert

Alert alert = new Alert("Message", "Cleared the Record store successfully...", null, AlertType.INFO);

static final Command backCommand = new Command("Back", Command.BACK, 0);

static final Command mainMenuCommand = new Command("Main", Command.SCREEN, 1);

static final Command saveCommand = new Command("Save", Command.OK, 2);

static final Command exitCommand = new Command("Exit", Command.STOP, 3);

String currentMenu = null;

// RecordStore object

RecordStore rs = null;

// Form components

DateField loanDate = new DateField("Repay Date", DateField.DATE);

TextField loanNumber = new TextField("Loan Number", null, 50, TextField.ANY);

TextField loanAmount = new TextField("Repay Amount", null, 20, TextField.NUMERIC);

public LoanMIDlet() {} // constructor

// Open a record store with the given name(打开记录存储)

public RecordStore openRS(String fileName)

{

try

{

//打开fileName记录存储,第二个参数true代表如果记录存储不存在的话就创建新的记录存储

//如果为false值则引发RecordStoreNotFoundException异常

rs = RecordStore.openRecordStore(fileName, true);

}

catch(RecordStoreException rse)

{

rse.printStackTrace();

}

return rs;

}

// Add a new record (loan) to the record store

//各个记录由字节数组表示,所以加入记录就意味着:加入字节数组到记录存储

//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();

}

}

// Use the enumeration object to delete each record in the record

//store删除记录存储

public void deleteRS()

{

try

{

RecordEnumeration re = enumerate();

while(re.hasNextElement())

{

int id = re.nextRecordId();

rs.deleteRecord(id);

}

showAlert();

}

catch (Exception e) { }

}

// Get the enumeration object.

public synchronized RecordEnumeration enumerate()

throws RecordStoreNotOpenException

{

return rs.enumerateRecords(null, null, false);

}

// Close the record store

public void closeRS()

throws RecordStoreNotOpenException, RecordStoreException

{

//检索记录存储中的记录总数,如果记录存储是空的则删除这个记录存储

if (rs.getNumRecords() == 0)

{

String fileName = rs.getName();

rs.closeRecordStore();

rs.deleteRecordStore(fileName);

}

else

{

rs.closeRecordStore();

}

}

// start the MIDlet

public void startApp() throws MIDletStateChangeException

{

display = Display.getDisplay(this);

// open the record source

try

{

//打开记录存储,没有的话就创建新的

openRS("myloan");

}

catch(Exception e) {}

menu = new List("Loan data", Choice.IMPLICIT);

menu.append("Add ", null);

menu.append("View ", null);

menu.append("Delete all entries", 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";

}

// Show the alert

public void showAlert()

{

try

{

alert.setTimeout(Alert.FOREVER);

display.setCurrent(alert);

}

catch(Exception e) {}

}

// Convert date to string

// The date Format used is 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";

}

// List the repayment details in the record store列出还贷记录信息

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";

}

// Handle command events

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"))

{

// add it to record store

try

{

String strNumber = loanNumber.getString();

String strAmount = loanAmount.getString();

String strDate = dateTostr (loanDate.getDate());

// Create the new record by concatenating the inputs

String strResult = strNumber + " ;" + strAmount + " ;" + strDate;

// Add it to the record store

addNewLoan(strResult);

}

catch(Exception e) {}

mainMenu();

}

}

else if (label.equals("Back"))

{

if(currentMenu.equals("List"))

{

// go back to menu

mainMenu();

}

else if(currentMenu.equals("Add"))

{

// go back to menu

mainMenu();

}

}

else

{

List down = (List)display.getCurrent();

switch(down.getSelectedIndex())

{

case 0: addLoan();break;

case 1: listItems();break;

case 2: deleteRS();break;

}

}

}

}

测试效果如下:

主界面

Add记录

Add完毕,保存

View记录

删除所有纪录



↑返回目录
前一篇: 介绍J2ME中的通用联网框架
后一篇: J2ME学习笔记(七)-----J2ME与XML的集成