Pages

Tuesday, November 6, 2012

J2ME – RMS local database

RmsDb.java
The Mobile Information Device Profile -- the platform for mobile Java applications -- provides a mechanism for MIDP applications to persistently store data locally, across multiple invocations and retrieve it later.

This persistent storage mechanism can be viewed as a simple record-oriented database model and is called the record management system (RMS).

The javax.microedition.rms.RecordStore class represents a RMS record store, called otherwise a database table. It provides several methods to manage as well as insert, update, and delete records in a record store.
The record store is created in platform-dependent locations, like nonvolatile device memory.

I implemented a simple java class working with RMS, that we can use in our j2me application:

D:\Programming\Java2ME\MobileApplicationDB\src\mobileapplicationdb\RmsDb.java

 1 package mobileapplicationdb;
 2 
 3 import javax.microedition.rms.RecordStore;
 4 
 5 public class RmsDb {
 6   private RecordStore rmsDb = null;
 7   static final String LOCAL_DB_NAME = "rms_db_example";
 8 
 9   public RmsDb() {
10   }
11 
12   public void openRecStore() {
13     try {
14       // The second parameter indicates that the record store
15       // should be created if it does not exist
16       rmsDb = RecordStore.openRecordStore(LOCAL_DB_NAME, true );
17     }
18     catch (Exception e) {
19         System.out.println(e.toString());        
20     }
21   }    
22   
23   public void closeRecStore() {
24     try {
25       rmsDb.closeRecordStore();
26     }
27     catch (Exception e) {
28       System.out.println(e.toString());        
29     }
30   }
31 
32   public void deleteRecStore() {
33     if (RecordStore.listRecordStores() != null) {
34       try {
35         RecordStore.deleteRecordStore(LOCAL_DB_NAME);
36       }
37       catch (Exception e) {
38         System.out.println(e.toString());        
39       }
40     }      
41   }
42 
43   public void writeRecord(String str) {
44     byte[] record = str.getBytes();
45     try {
46       rmsDb.addRecord(record, 0, record.length);      
47     }
48     catch (Exception e) {
49       System.out.println(e.toString());        
50     }
51   }
52 
53   public String readRecords() {
54     String res = "";            
55     StringBuffer buf = new StringBuffer();                
56     try {
57       byte[] recData = null;
58       int intLen;
59 
60       for (int i = 1; i <= rmsDb.getNumRecords(); i++) {        
61           recData = new byte[rmsDb.getRecordSize(i)];       
62           intLen = rmsDb.getRecord(i, recData, 0);
63           res = "Record no." + i + ": " + new String(recData, 0, intLen)+"\n";       
64           buf.append(res);        
65       }
66       res = buf.toString();
67     }
68     catch (Exception e) {
69       System.out.println(e.toString());        
70     }
71     return res;
72   }
73 
74 }
-->

No comments:

Post a Comment