Record Management System From Getting Started to Three Mass Plus Series

zhaozj2021-02-16  54

The previous article introduces the basic concepts of Record Management System and the problem of object serialization. Now we mainly introduce the use of the RecordStore class. In the Sun's website, you can provide a RMSANalyzer class, you can use him in your project. To debug your program.

Record Store Discovery You can get the Record Store in MIDlet Suites by calling RecordStore.ListRecordStores (), this static method returns an array of String types, each represents the name of the Record Store, if there is no Record Store, will return null, method RMSANALYZER .annlyzeall () gets the Record Store by calling ListRecordStores () and then analyzes each Record Store by method analysis ().

Public void analynd () {

String [] names = RecordStore.ListRecordStore ();

For (int i = 0;

Names! = NULL && I

i) {

Analyze (Names [I]);

}

}

Note that the array names listed are the Record Store of the MIDlet Suite. A method for the Record Store for any other MIDlet Suites is not provided in MIDP. In MIDP 1.0, the Record Store is invisible outside of the MIDLET Suites. In MIDP 2.0, MIDP 2.0 can specify a Record Store as a shared, but Other Suite want to know his name to access it.

Opening and Closing Record Store RecordStore.OpenRecordStore () is used to open a Record Store, which can also be used to create a Record Store, this static method returns an object of a Record Store, below is Rmsanalyzer.analyze ().

Public void analyze (string rsname) {

RecordStore RS = NULL;

Try {

RS = RecordStore.OpenRecordStore (RSName, False);

Analyze (RS); // Call overloaded Method

} catch (recordstoreException e) {

Logger.Exception (RSName, E);

} finally {

Try {

Rs.closecordstore ();

} catch (recordstoreException e) {

// ignore this Exception

}

}

}

The second parameter of OpenRecordStore () indicates that if the Record Store does not exist, in MIDP2.0, if you want to open a Record Store created in other MIDlet Suite, you should use the following method.

...

String name = "mysharedrs";

String vendor = "ericgiguere.com";

String suite = "testsuite";

RecordStore RS =

RecordStore.OpenRecordStore (Name, vendor, suite);

...

The name of Vendor and Suite should be consistent with the contents of MIDlet Suite's Manifest and Jad. When you have completed the operation of the Record Store, you should call the RecordStore.closecordStore () to close it, an instance of a RecordStore is unique in a MIDlet Suite, if the same name is called again OpenRecordStore (), the same instance will be returned Such a plurality of MIDlets in sharing a Record Store, each Record Store will trace the number of times it is opened, this Record Store is completely closed until the closerecordStore () called the same number is completely closed, and the Record Store that has been closed is performed. Operation can result in thrown

Recordstorenotopenexception.

Creating Record Store Creates a private Record Store, set the second parameter to True to call OpenRecordStore (), ...

// Create a Record Store

RecordStore RS = NULL;

Try {

RS = RecordStore.OpenRecordStore ("Myrs", True);

} catch (recordstoreException e) {

// COULDN'T Open it or create it

}

If you want to create a shared Record Store, use the OpenRecordStore of the four parameter variables ()

INT Authmode = RecordStore.AuthMode_any;

Boolean Writable = True;

RS = RecordStore.OpenRecordStore ("Myrs", True,

Authmode, Writable;

When the second parameter is True and the Record Store does not exist, the back two parameters control his authorization mode and can be writable, the authorization mode decides whether other MIDlet Suite has access to the Record Store, two possible modes are RecordStore.AuthMode_Private (only Suite can access) and RecordStore.AuthMode_any (any Suite can be accessed), can be used to control whether other Suite can modify the Record Store, if false, then only Suite can be modified, Other can only be read. Note that the SUITE can call RecordStore.seTMode () at any time to modify its authorization and read and write mode, for example:

Rs.SetMode (RecordStore.AuthMode_any, false); in fact, it is best to create a Record Store, authorization mode is RecordStore.AuthMode_private.

Add and Updating Records record is an array of bytes, you can add a new record to an open Record Store by calling RecordStore.AddRecord ().

Byte [] data = new byte [] {0, 1, 2, 3};

INT RecordId;

Recordid = rs.addRecord (Data, 0, Data.Length);

If the first parameter is null, then you can add an empty record. The second and third parameters illustrate the starting point of the byte array and the total number of bytes starting from the starting point. If the addition of success returns a new recorded Record ID, if the failure will throw an exception, such as the RecordStorefullexception. Update the recorded content by calling RecordStore.seTRecord ().

INT recordid = ...; // Some Record ID

Byte [] data = new byte [] {0, 10, 20, 30};

Rs.SetRecord (RecordID, Data, 1, 2);

// Replaces All Data IN Record With 10, 20

You can't add a record, you must first convert the record into an array, then call the added function, by calling RecordStore.getNextRecordidId () You can get the next call addRecord () will get the RECORD ID, this value is used now Any value is large.

Reading Records Want to read records, there are two ways. The first is to assign an array of suitable sizes and then copy the contents of the record.

INT recordid = .... // Some Record ID

Byte [] data = rs.getRecord (RecordID);

The second method is to copy the array to a pre-allocated byte array, specify the origin of the copy and return the number of bytes replicated.

INT recordid = ...; // Some Record ID

Byte [] data = ...; // an Array

INT offset = ...; // the starting offset

Int numcopied = rs.getRecord (RecordID, DATA, OFFSET);

The size of the array must be sufficient enough to accommodate data, otherwise it will throw java.lang.arayindexoutofboundSexception. Use RecordStore.GetRecordsize () to assign array spaces to be appropriate. In fact, the first method is equivalent

Byte [] data = new byte [rs.getRecordsize (RecordID)];

Rs.getRecord (RecordID, DATA, 0);

The second method facilitates reducing memory distribution. When you want to traverse a set of records, you can complete a large search in combination with GetNexTrecordID () and GetRecordsize ().

INT nextID = rs.getnexTrecordId ();

BYTE [] DATA = NULL;

For (int ID = 0; ID

Try {

INT size = rs.getRecordsize (ID);

IF (Data == Null || data.length

Data = new byte [size];

}

Rs.GetRecord (ID, DATA, 0);

ProcessRecord (RS, ID, DATA, SIZE); // Process IT

} catch (invalidRecordidexception e) {

// Ignore, Move to Next Record

} catch (recordstoreException e) {

HandleError (RS, ID, E); // Call An Error Routine

}

}

A better way is to use RecordStore.EnumeRateRecords () to traverse records. Deleting Records and Record Stores You can delete records by calling RecordStore.deleteRecord ()

INT recordid = ...; // Some Record ID

Rs.deleteRecord (RecordID);

Once the record is deleted, any operation of the record will cause the INVALIDRECORDIDEXCEPTION to remove the Record Store by calling RecordStore.DeleteRecordStore ().

Try {

RecordStore.deleteRecordStore ("MyRS");

} catch (recordstorenotfoundexception e) {

// No Such Record Store

} catch (recordstoreException e) {

// SomeBody Has it Open

}

The Record Store can only be deleted from the Suite's MIDlet that is owned when not open.

Other Operations getLastModified () Returns the time, format, and system.currenttimemillis () that finally modifies the Record Store.

GetName () get the name of the Record Store.

GetNumRecords () Returns the number of records recorded in the Record Store.

GetSize () Returns the entire size of the Record Store, including the size of the record and the system to implement the RECORD Store.

GetSizeavailable () Returns the space that can be used in the Record Store,

getversion () Returns the number of version of the Record Store, this number is more than 0, each Record Store is modified, this number will be added automatically.

A MIDLET can track the Record Store by registering a listener, through addRecordListener () and deleteRecordListener ().

The Rmsanalyzer Class finally provides a class analyzing the Record Store, you can use it like this.

RecordStore Rs = ...; // Open the Record Store

Rmsanalyzer analyzer = new rmsanalyzer ();

Analyzer.Analyze (RS);

Usually analyzes output to system.out, the style is as follows:

==============================================================================================================================================

Record Store: RecordStore2

Number of records = 4

Total Size = 304

Version = 4

Last Modified = 1070745507485

Size available = 975950

Record # 1 of longth 56 bytes

5F 62 06 75 2e 6b 1c 42 58 3f _b.u.k.bx?

1e 2e 6A 24 74 29 7C 56 30 32 ..j $ T) | V02

5F 67 5A 13 47 7A 77 68 7D 49 _GZ.Gzwh} i50 74 50 20 6B 14 78 60 58 4B PTP K.X`XK

1A 61 67 20 53 65 0A 2F 23 2b .AG se./#

16 42 10 4e 37 6f .b.n7o

Record # 2 of longth 35 bytes

22 4B 19 22 15 7D 74 1F 65 26 "K."} T. E &

4e 1e 50 62 50 6e 4f 47 6A 26 N.PBPNOGJ &

31 11 74 36 7A 0A 33 51 61 0e 1.t6z.3qa.

04 75 6A 2A 2a .uj **

Record # 3 of longth 5 bytes

47 04 43 22 1F g.c.

Record # 4 of longth 57 bytes

6B 6F 42 1D 5B 65 2F 72 0F 7A Kob. [E / R.Z

2A 6E 07 57 51 71 5F 68 4C 5C * N.WQQ_HL /

1A 2A 44 7B 02 7D 19 73 4F 0B. * D {.}. SO.

75 03 34 58 17 19 5e 6a 5e 80 u.4x .. ^ j ^?

2A 39 28 5C 4A 4e 21 57 4D 75 * 9 (/ JN! WMU

80 68 06 26 3B 77 33? H. &; W3

Actual Size of Records = 153

-----------------------------------------

This style is convenient in the WTK, when testing in the actual device, you may want to output the analysis to the serial port or send it to the servlet through the network, you can implement the Logger interface by defining your own class, then put this class As the parameters of the RMSANALYZER constructor. The following is the source code.

Package com.ericgiguere;

Import java.io. *;

Import javax.microedition.rms. *;

// Analyzes The Contents of a Record Store.

// by Default Prints the analysis to system.out,

// but you can change this by import your money Your, IMPLEMENTING YOUR

// OWN Logger.

Public class rmsanalyzer {

// The logging interface.

Public interface logger {

Void Logend (RecordStore RS);

Void Logexception (String Name, Throwable E);

Void Logexception (RecordStore RS, Throwable E);

Void LogRecord (RecordStore RS, INT ID,

Byte [] data, int size;

Void logStart (RecordStore RS);

}

PRIVATE LOGGER logger;

// constructs an analysis.

Public rmsanalyzer () {

this (null);

}

// Constructs an Analyzer That Logs to the Given Logger.

Public rmsanalyzer (Logger Logger) {

THIS.LOGGER = (logger! = null) Logger: New systemlogger ();

}

// Open the record store Owned by this Midlet Suite

// and analyze their contents.

Public void analynd () {

String [] names = RecordStore.ListRecordStore ();

For (int i = 0;

Names! = NULL && I

i) {

Analyze (Names [I]);

}

}

// Open a replaord store by name and analysis its contents.

Public void analyze (string rsname) {

RecordStore RS = NULL;

Try {

RS = RecordStore.OpenRecordStore (RSName, False);

Analyze (RS);

} catch (recordstoreException e) {

Logger.logexception (RSName, E);

} finally {

Try {

Rs.closecordstore ();

} catch (recordstoreException e) {

// ignore this Exception

}

}

}

// analyze the contents of an open record store sale

// a Simple Brute Force Search Through The Record Store.

Public synchronized void analysis (RecordStore RS) {

Try {

Logger.logstart (RS);

Int lastid = rs.getNextRecordId ();

INT NUMRECORDS = rs.getnumRecords ();

INT count = 0;

BYTE [] DATA = NULL;

For (int id = 0;

Id

id) {

Try {

INT size = rs.getRecordsize (ID);

// Make Sure Data Array Is Big Enough,

// Plus Add Some for GROWTH

IF (Data == Null || data.length

Data = new byte [Size 20];

}

Rs.GetRecord (ID, DATA, 0);

Logger.logRecord (RS, ID, DATA, SIZE);

count; // only increase if record

}

Catch (InvalidRecordidexception E) {

//just ignore and move to the next one

}

Catch (RecordStoreException E) {

Logger.logexception (RS, E);

}

}

} catch (recordstoreException e) {

Logger.logexception (RS, E);

} finally {

Logger.logend (RS);

}

// a logger what Outputs to a printstream.

Public Static Class PrintStreamLogger Implements Logger {

Public Static Final INT COLS_MIN = 10;

Public static final int cols_default = 20;

PRIVATE INT COLS;

Private int numbytes;

Private stringbuffer hbuf;

Private stringbuffer CBUF;

Private stringbuffer PBUF;

Private printStream out;

Public PrintStreamLogger (PrintStream out) {

THIS (OUT, COLS_DEFAULT);

}

Public PrintStreamLogger (PrintStream out, int cols) {

THIS.out = OUT;

THIS.COLS = (COLS> COLS_MIN? COLS: COLS_MIN);

}

Private char convertchar (char CH) {

IF (CH <0x20) return '.';

Return ch;

}

Public void Logend (RecordStore RS) {

Out.println ("/ Nactual Size of Records ="

NumBytes);

Printchar ('-', cols * 4 1);

HBUF = NULL;

CBUF = NULL;

PBUF = NULL;

}

Public void Logexception (String Name, Throwable E) {

Out.println ("Exception While Analyzing"

Name ":" e);

}

Public void Logexception (RecordStore RS, Throwable E) {

String name;

Try {

Name = rs.getname ();

} catch (RecordStoreException RSE) {

Name = ""

}

LOGEXCEPTION (Name, E);

}

Public Void LogRecord (RecordStore RS, INT ID,

Byte [] DATA, INT LEN) {

IF (Len <0 && Data! = NULL) {

Len = data.length;

}

Hbuf.setlength (0);

Cbuf.setlength (0);

NumBytes = LEN;

Out.println ("Record #" ID "of Length"

LEN "BYTES");

For (int i = 0; i

INT B = Math.Abs ​​(Data [I]);

String hstr = integer.tohexstring (b);

IF (B <0x10) {

HBUF.Append ('0');

HBUF.Append (HSTR);

HBUF.Append ('');

CBUF.Append (ConvertChar (CHAR) B));

IF (Cbuf.Length () == COLS) {

Out.println (HBUF "" CBUF);

Hbuf.setlength (0);

Cbuf.setlength (0);

}

}

Len = cbuf.length ();

IF (len> 0) {

While (Len

HBUF.Append ("");

CBUF.Append ('');

}

Out.println (HBUF "" CBUF);

}

}

Public void logStart (RecordStore RS) {

HBUF = New StringBuffer (cols * 3);

CBUF = New StringBuffer;

PBUF = new stringbuffer ();

Printchar ('=', COLS * 4 1);

NumBytes = 0;

Try {

Out.println ("RECORD Store:"

rs.getname ());

OUT.PRINTLN ("Number of Records ="

rs.getnumRecords ());

Out.println ("Total size ="

rs.getsize ());

Out.println ("Version ="

rs.getversion ());

Out.println ("Last Modified ="

rs.getlastmodified ());

Out.println ("Size Available ="

rs.getsizeavailable ());

OUT.PRINTLN ("");

} catch (recordstoreException e) {

LOGEXCEPTION (RS, E);

}

}

Private void printchar (char ch, int num) {

Pbuf.setLength (0);

While (NUM -> 0) {

PBUF.Append (CH);

}

Out.println (pbuf.tostring ());

}

}

// a logger what outputs to system.out.

Public Static Class SystemLogger

Extends printstreamlogger {

Public systemlogger () {

SUPER (System.out);

}

Public systemlogger (int cols) {

SUPER (System.out, Cols);

}

}

转载请注明原文地址:https://www.9cbs.com/read-20094.html

New Post(0)