Java/J2ME/Database Persistence
Содержание
- 1 Mixed Record Enumeration Example
- 2 Persistence: storing and showing game scores
- 3 Persistent Ranking MIDlet
- 4 Read and write to the record store.
- 5 Record Enumeration Example
- 6 Record MIDlet
- 7 Search Example
- 8 Search Mixed Record Data Type Example
- 9 Sort Mixed Record Data Type Example
- 10 Sort Record Example
- 11 Store Database
- 12 Test the RMS listener methods
- 13 Use streams to read and write Java data types to the record store.
- 14 Write Read Mixed Data Types Example
Mixed Record Enumeration Example
/*
J2ME: The Complete Reference
James Keogh
Publisher: McGraw-Hill
ISBN 0072227109
*/
//jad file (please verify the jar size)
/*
MIDlet-Name: MixedRecordEnumerationExample
MIDlet-Version: 1.0
MIDlet-Vendor: MyCompany
MIDlet-Jar-URL: MixedRecordEnumerationExample.jar
MIDlet-1: MixedRecordEnumerationExample, ,
MixedRecordEnumerationExample
MicroEdition-Configuration: CLDC-1.0
MicroEdition-Profile: MIDP-1.0
MIDlet-JAR-SIZE: 100
*/
import javax.microedition.rms.*;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import java.io.*;
public class MixedRecordEnumerationExample
extends MIDlet implements CommandListener
{
private Display display;
private Alert alert;
private Form form;
private Command exit;
private Command start;
private RecordStore recordstore = null;
private RecordEnumeration recordEnumeration = null;
public MixedRecordEnumerationExample ()
{
display = Display.getDisplay(this);
exit = new Command("Exit", Command.SCREEN, 1);
start = new Command("Start", Command.SCREEN, 1);
form = new Form("Mixed RecordEnumeration");
form.addCommand(exit);
form.addCommand(start);
form.setCommandListener(this);
}
public void startApp()
{
display.setCurrent(form);
}
public void pauseApp()
{
}
public void destroyApp( boolean unconditional )
{
}
public void commandAction(Command command, Displayable displayable)
{
if (command == exit)
{
destroyApp(true);
notifyDestroyed();
}
else if (command == start)
{
try
{
recordstore = RecordStore.openRecordStore(
"myRecordStore", true );
}
catch (Exception error)
{
alert = new Alert("Error Creating",
error.toString(), null, AlertType.WARNING);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert);
}
try
{
byte[] outputRecord;
String outputString[] = {"First Record",
"Second Record", "Third Record"};
int outputInteger[] = {15, 10, 5};
boolean outputBoolean[] = {true, false, true};
ByteArrayOutputStream outputStream =
new ByteArrayOutputStream();
DataOutputStream outputDataStream =
new DataOutputStream(outputStream);
for (int x = 0; x < 3; x++)
{
outputDataStream.writeUTF(outputString[x]);
outputDataStream.writeBoolean(outputBoolean[x]);
outputDataStream.writeInt(outputInteger[x]);
outputDataStream.flush();
outputRecord = outputStream.toByteArray();
recordstore.addRecord(outputRecord, 0,
outputRecord.length);
}
outputStream.reset();
outputStream.close();
outputDataStream.close();
}
catch ( Exception error)
{
alert = new Alert("Error Writing",
error.toString(), null, AlertType.WARNING);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert);
}
try
{
StringBuffer buffer = new StringBuffer();
byte[] byteInputData = new byte[300];
ByteArrayInputStream inputStream = new ByteArrayInputStream(byteInputData);
DataInputStream inputDataStream =
new DataInputStream(inputStream);
recordEnumeration = recordstore.enumerateRecords(
null, null, false);
while (recordEnumeration.hasNextElement())
{
recordstore.getRecord(recordEnumeration.nextRecordId(),
byteInputData, 0);
buffer.append(inputDataStream.readUTF());
buffer.append("\n");
buffer.append(inputDataStream.readBoolean());
buffer.append("\n");
buffer.append(inputDataStream.readInt());
buffer.append("\n");
alert = new Alert("Reading", buffer.toString(),
null, AlertType.WARNING);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert);
}
inputStream.close();
}
catch (Exception error)
{
alert = new Alert("Error Reading",
error.toString(), null, AlertType.WARNING);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert);
}
try
{
recordstore.closeRecordStore();
}
catch (Exception error)
{
alert = new Alert("Error Closing",
error.toString(), null, AlertType.WARNING);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert);
}
if (RecordStore.listRecordStores() != null)
{
try
{
RecordStore.deleteRecordStore("myRecordStore");
recordEnumeration.destroy();
}
catch (Exception error)
{
alert = new Alert("Error Removing",
error.toString(), null, AlertType.WARNING);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert);
}
}
}
}
}
Persistence: storing and showing game scores
/*
* RMSGameScores.java
* Copyright (c) 2000 Sun Microsystems, Inc. All Rights Reserved.
*
* Author: Srikanth Raju
*
* This software is the confidential and proprietary information of Sun
* Microsystems, Inc. ("Confidential Information"). You shall not
* disclose such Confidential Information and shall use it only in
* accordance with the terms of the license agreement you entered into
* with Sun.
*
* SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE
* SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
* IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR ANY DAMAGES
* SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING
* THIS SOFTWARE OR ITS DERIVATIVES.
*/
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
import javax.microedition.rms.RecordComparator;
import javax.microedition.rms.RecordEnumeration;
import javax.microedition.rms.RecordFilter;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreException;
/**
* A class used for storing and showing game scores.
*/
public class RMSGameScores extends MIDlet implements RecordFilter,
RecordComparator {
/*
* The RecordStore used for storing the game scores.
*/
private RecordStore recordStore = null;
/*
* The player name to use when filtering.
*/
public static String playerNameFilter = null;
/**
* The constuctor opens the underlying record store, creating it if
* necessary.
*/
public RMSGameScores() {
// Create a new record store for this example
try {
recordStore = RecordStore.openRecordStore("scores", true);
} catch (RecordStoreException rse) {
System.out.println("Record Store Exception in the ctor." + rse);
rse.printStackTrace();
}
}
/**
* startApp()
*/
public void startApp() throws MIDletStateChangeException {
RMSGameScores rmsgs = new RMSGameScores();
rmsgs.addScore(100, "Alice");
rmsgs.addScore(120, "Bill");
rmsgs.addScore(80, "Candice");
rmsgs.addScore(40, "Dean");
rmsgs.addScore(200, "Ethel");
rmsgs.addScore(110, "Farnsworth");
rmsgs.addScore(220, "Alice");
RMSGameScores.playerNameFilter = "Alice";
System.out
.println("Print all scores followed by Scores for Farnsworth");
rmsgs.printScores();
}
/*
* Part of the RecordFilter interface.
*/
public boolean matches(byte[] candidate) throws IllegalArgumentException {
// If no filter set, nothing can match it.
if (this.playerNameFilter == null) {
return false;
}
ByteArrayInputStream bais = new ByteArrayInputStream(candidate);
DataInputStream inputStream = new DataInputStream(bais);
String name = null;
try {
int score = inputStream.readInt();
name = inputStream.readUTF();
} catch (EOFException eofe) {
System.out.println(eofe);
eofe.printStackTrace();
} catch (IOException eofe) {
System.out.println(eofe);
eofe.printStackTrace();
}
return (this.playerNameFilter.equals(name));
}
/*
* Part of the RecordComparator interface.
*/
public int compare(byte[] rec1, byte[] rec2) {
// Construct DataInputStreams for extracting the scores from
// the records.
ByteArrayInputStream bais1 = new ByteArrayInputStream(rec1);
DataInputStream inputStream1 = new DataInputStream(bais1);
ByteArrayInputStream bais2 = new ByteArrayInputStream(rec2);
DataInputStream inputStream2 = new DataInputStream(bais2);
int score1 = 0;
int score2 = 0;
try {
// Extract the scores.
score1 = inputStream1.readInt();
score2 = inputStream2.readInt();
} catch (EOFException eofe) {
System.out.println(eofe);
eofe.printStackTrace();
} catch (IOException eofe) {
System.out.println(eofe);
eofe.printStackTrace();
}
// Sort by score
if (score1 > score2) {
return RecordComparator.FOLLOWS;
} else if (score1 < score2) {
return RecordComparator.PRECEDES;
} else {
return RecordComparator.EQUIVALENT;
}
}
/**
* Add a new score to the storage.
*
* @param score
* the score to store.
* @param playerName
* the name of the play achieving this score.
*/
public void addScore(int score, String playerName) {
// Each score is stored in a separate record, formatted with
// the score, followed by the player name.
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream outputStream = new DataOutputStream(baos);
try {
// Push the score into a byte array.
outputStream.writeInt(score);
// Then push the player name.
outputStream.writeUTF(playerName);
} catch (IOException ioe) {
System.out.println(ioe);
ioe.printStackTrace();
}
// Extract the byte array
byte[] b = baos.toByteArray();
try {
// Add it to the record store
recordStore.addRecord(b, 0, b.length);
} catch (RecordStoreException rse) {
System.out.println(rse);
rse.printStackTrace();
}
}
/**
* A helper method for the printScores methods.
*/
private void printScoresHelper(RecordEnumeration re) {
try {
while (re.hasNextElement()) {
int id = re.nextRecordId();
ByteArrayInputStream bais = new ByteArrayInputStream(
recordStore.getRecord(id));
DataInputStream inputStream = new DataInputStream(bais);
try {
int score = inputStream.readInt();
String playerName = inputStream.readUTF();
System.out.println(playerName + " = " + score);
} catch (EOFException eofe) {
System.out.println(eofe);
eofe.printStackTrace();
}
}
} catch (RecordStoreException rse) {
System.out.println(rse);
rse.printStackTrace();
} catch (IOException ioe) {
System.out.println(ioe);
ioe.printStackTrace();
}
}
/**
* This method prints all of the scores sorted by game score.
*/
public void printScores() {
try {
// Enumerate the records using the comparator implemented
// above to sort by game score.
// No RecordFilter here. All records in the RecordStore
RecordEnumeration re = recordStore.enumerateRecords(null, this,
true);
// Print all scores
System.out.println("Print all scores...");
printScoresHelper(re);
// Enumerate records respecting a RecordFilter
re = recordStore.enumerateRecords(this, this, true);
//Print scores for Farnsworth
System.out.println("Print scores for : " + this.playerNameFilter);
printScoresHelper(re);
} catch (RecordStoreException rse) {
System.out.println(rse);
rse.printStackTrace();
}
}
/**
* pauseApp()
*/
public void pauseApp() {
System.out.println("pauseApp()");
}
/**
* destroyApp()
*
* This closes our open RecordStore when we are destroyed.
*
* @param cond
* true if this is an unconditional destroy false if it is not
* (ignored here and treated as unconditional)
*/
public void destroyApp(boolean cond) {
System.out.println("destroyApp( )");
try {
if (recordStore != null)
recordStore.closeRecordStore();
} catch (Exception ignore) {
// ignore this
}
}
}
Persistent Ranking MIDlet
/*
J2ME in a Nutshell
By Kim Topley
ISBN: 0-596-00253-X
*/
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.InputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import javax.microedition.rms.RecordComparator;
import javax.microedition.rms.RecordEnumeration;
import javax.microedition.rms.RecordFilter;
import javax.microedition.rms.RecordListener;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreException;
import java.util.Vector;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.rumand;
import javax.microedition.lcdui.rumandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.List;
import javax.microedition.lcdui.Screen;
import javax.microedition.lcdui.StringItem;
import javax.microedition.lcdui.TextField;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
import javax.microedition.rms.RecordEnumeration;
import javax.microedition.rms.RecordListener;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreException;
public class PersistentRankingMIDlet extends MIDlet
implements CommandListener, RecordListener, Runnable {
private Command exitCommand;
private Command okCommand;
private Command cancelCommand;
private Command newCommand;
private Command checkCommand;
private Command detailsCommand;
private Command backCommand;
private Command deleteCommand;
private Display display;
private TextField isbnField;
private StringItem isbnDisplay;
private StringItem titleDisplay;
private StringItem rankingDisplay;
private StringItem reviewDisplay;
private StringItem checkTitle;
private Form isbnForm;
private Form searchForm;
private Form resultForm;
private Form checkForm;
private List bookList;
private Vector bookInfoList;
private Thread searchThread;
private BookStore bookStore;
private BookInfo searchBookInfo;
protected void startApp() throws MIDletStateChangeException {
if (display == null) {
initialize();
// If there are any books in the
// book store, display the list.
// Otherwise, start with the ISBN form.
display.setCurrent(getSelectionScreen());
}
}
protected void pauseApp() {
}
protected void destroyApp(boolean unconditional)
throws MIDletStateChangeException {
// Close the book store
if (bookStore != null) {
try {
bookStore.removeRecordListener(this);
bookStore.close();
} catch (RecordStoreException ex) {
}
}
}
public void commandAction(Command cmd, Displayable d) {
if (cmd == exitCommand) {
try {
destroyApp(true);
} catch (MIDletStateChangeException ex) {
}
notifyDestroyed();
} else if (cmd == okCommand) {
String isbn = isbnField.getString().trim();
if (!isbn.equals("")) {
isbnDisplay.setText(isbn);
display.setCurrent(searchForm);
searchForBook(new BookInfo(isbn));
}
} else if (cmd == cancelCommand) {
searchThread = null;
isbnField.setString(null);
display.setCurrent(getSelectionScreen());
} else if (cmd == newCommand) {
isbnField.setString(null);
display.setCurrent(isbnForm);
} else if (cmd == detailsCommand || cmd == List.SELECT_COMMAND) {
int index = bookList.getSelectedIndex();
searchBookInfo = (BookInfo)bookInfoList.elementAt(index);
isbnDisplay.setText(searchBookInfo.getIsbn());
showBookInfo(searchBookInfo);
} else if (cmd == deleteCommand) {
int index = bookList.getSelectedIndex();
BookInfo bookInfo = (BookInfo)bookInfoList.elementAt(index);
try {
bookStore.deleteBook(bookInfo);
} catch (RecordStoreException ex) {
System.out.println("Delete failed: " + ex);
}
} else if (cmd == checkCommand) {
String isbn = searchBookInfo.getIsbn();
checkTitle.setText(searchBookInfo.getTitle());
display.setCurrent(checkForm);
searchForBook(searchBookInfo);
} else if (cmd == backCommand) {
display.setCurrent(getSelectionScreen());
}
}
public void searchForBook(BookInfo info) {
searchBookInfo = info;
searchThread = new Thread(this);
searchThread.start();
}
public void recordAdded(RecordStore recordStore, int recordId) {
// Update the book list
populateBookList();
}
public void recordChanged(RecordStore recordStore, int recordId) {
// Update the book list
populateBookList();
}
public void recordDeleted(RecordStore recordStore, int recordId) {
// Update the book list
populateBookList();
}
public void run() {
try {
boolean found = Fetcher.fetch(searchBookInfo);
if (searchThread == Thread.currentThread()) {
if (found && searchBookInfo.getTitle() != null) {
// Display the book details
showBookInfo(searchBookInfo);
// Add the new book to the book store
bookStore.saveBookInfo(searchBookInfo);
} else {
Alert alert = new Alert("Book not found", null,
null, AlertType.ERROR);
alert.setTimeout(Alert.FOREVER);
alert.setString("No book with ISBN " +
searchBookInfo.getIsbn() +
" was found.");
isbnField.setString(null);
display.setCurrent(alert, getSelectionScreen());
}
}
} catch (Throwable ex) {
if (searchThread == Thread.currentThread()) {
Alert alert = new Alert("Search Failed", null,
null, AlertType.ERROR);
alert.setTimeout(Alert.FOREVER);
alert.setString("Search failed:\n" + ex.getMessage());
isbnField.setString(null);
display.setCurrent(alert, getSelectionScreen());
}
}
}
// Shows book details on the result screen
private void showBookInfo(BookInfo info) {
titleDisplay.setText(info.getTitle());
int ranking = info.getRanking();
int lastRanking = info.getLastRanking();
int change = ranking - lastRanking;
String rankingText =
ranking == 0 ? "" :
String.valueOf(ranking);
if (change > 0) {
rankingText += ", down by " + change;
} else if (change < 0) {
rankingText += ", UP by " + (-change);
}
rankingDisplay.setText(rankingText);
int reviews = info.getReviews();
int lastReviews = info.getLastReviews();
change = reviews - lastReviews;
String reviewText =
reviews == 0 ? "" :
String.valueOf(reviews);
if (change > 0) {
reviewText += ", up by " + change;
}
reviewDisplay.setText(reviewText);
display.setCurrent(resultForm);
}
// If there are any books in the
// book store, display the list.
// Otherwise, start with the ISBN form.
private Screen getSelectionScreen() {
return
bookInfoList.isEmpty() ? (Screen)isbnForm : (Screen)bookList;
}
// Populates the list of books
private void populateBookList() {
// Clear out any existing content
int count = bookList.size();
for (int i = 0; i < count; i++) {
bookList.delete(0);
}
bookInfoList.removeAllElements();
// Add an entry for each book in the store
try {
RecordEnumeration e = bookStore.getBooks();
while (e.hasNextElement()) {
int id = e.nextRecordId();
BookInfo info = bookStore.getBookInfo(id);
bookInfoList.addElement(info);
String title = info.getTitle();
if (title == null || title.equals("")) {
title = info.getIsbn();
}
bookList.append(title, null);
}
e.destroy();
} catch (Exception ex) {
// Just leave an empty list.
}
// The ISBN list should have an exit command
// only if the List screen is empty.
isbnForm.removeCommand(exitCommand);
if (bookInfoList.isEmpty()) {
isbnForm.addCommand(exitCommand);
}
}
private void initialize() {
display = Display.getDisplay(this);
// Open the book store
bookStore = new BookStore();
exitCommand = new Command("Exit", Command.EXIT, 0);
okCommand = new Command("OK", Command.OK, 0);
cancelCommand = new Command("Cancel", Command.CANCEL, 0);
newCommand = new Command("New", Command.SCREEN, 1);
detailsCommand = new Command("Details", Command.OK, 0);
checkCommand = new Command("Check", Command.OK, 0);
backCommand = new Command("Back", Command.CANCEL, 1);
deleteCommand = new Command("Delete", Command.SCREEN, 1);
bookList = new List("Books", List.IMPLICIT);
bookList.addCommand(detailsCommand);
bookList.addCommand(newCommand);
bookList.addCommand(deleteCommand);
bookList.addCommand(exitCommand);
bookInfoList = new Vector();
isbnForm = new Form("Book Query");
isbnForm.append("Enter an ISBN and press OK:");
isbnField = new TextField("", null, 10, TextField.ANY);
isbnForm.append(isbnField);
isbnForm.addCommand(okCommand);
isbnForm.addCommand(exitCommand);
isbnForm.addCommand(backCommand);
searchForm = new Form("Book Search");
searchForm.append("Searching for ISBN\n");
isbnDisplay = new StringItem(null, null);
searchForm.append(isbnDisplay);
searchForm.append("\nPlease wait....");
searchForm.addCommand(cancelCommand);
checkForm = new Form("Details Update");
checkForm.append("Getting details for\n");
checkTitle = new StringItem(null, null);
checkForm.append(checkTitle);
checkForm.append(" from amazon.ru\nPlease wait....");
checkForm.addCommand(cancelCommand);
resultForm = new Form("Search Results");
titleDisplay = new StringItem("Book title: ", null);
rankingDisplay = new StringItem("Ranking: ", null);
reviewDisplay = new StringItem("Reviews: ", null);
resultForm.append(titleDisplay);
resultForm.append(rankingDisplay);
resultForm.append(reviewDisplay);
resultForm.addCommand(backCommand);
resultForm.addCommand(checkCommand);
// Register for events from all of the forms
isbnForm.setCommandListener(this);
searchForm.setCommandListener(this);
resultForm.setCommandListener(this);
bookList.setCommandListener(this);
// Listen for changes in the content of the book store
bookStore.addRecordListener(this);
// Install the books held in the record store
populateBookList();
}
}
// A class that implements a persistent store
// of books, keyed by ISBN.
class BookStore implements RecordComparator, RecordFilter {
// The name of the record store used to hold books
private static final String STORE_NAME = "BookStore";
// The record store itself
private RecordStore store;
// ISBN to be used during a filter operation
private String searchISBN;
// Creates a bookstore and opens it
public BookStore() {
try {
store = RecordStore.openRecordStore(STORE_NAME, true);
} catch (RecordStoreException ex) {
System.err.println(ex);
}
}
// Closes the bookstore
public void close() throws RecordStoreException {
if (store != null) {
store.closeRecordStore();
}
}
// Gets the number of books in the book store
public int getBookCount() throws RecordStoreException {
if (store != null) {
return store.getNumRecords();
}
return 0;
}
// Adds a listener to the book store
public void addRecordListener(RecordListener l) {
if (store != null) {
store.addRecordListener(l);
}
}
// Removes a listener from the book store
public void removeRecordListener(RecordListener l) {
if (store != null) {
store.removeRecordListener(l);
}
}
// Gets a sorted list of all of the books in
// the store.
public RecordEnumeration getBooks() throws RecordStoreException {
if (store != null) {
return store.enumerateRecords(null, this, false);
}
return null;
}
// Gets a BookInfo from a store record
// given its ISBN
public BookInfo getBookInfo(String isbn) throws RecordStoreException,
IOException {
BookInfo bookInfo = null;
searchISBN = isbn;
// Look for a book with the given ISBN
RecordEnumeration e = store.enumerateRecords(
this, null, false);
// If found, get its identifier and
// fetch its BookInfo object
if (e.numRecords() > 0) {
int id = e.nextRecordId();
bookInfo = getBookInfo(id);
}
// Release the enumeration
e.destroy();
return bookInfo;
}
// Gets a BookInfo from a store record
// given its record identifier
public BookInfo getBookInfo(int id) throws RecordStoreException,
IOException {
byte[] bytes = store.getRecord(id);
DataInputStream is = new DataInputStream(
new ByteArrayInputStream(bytes));
String isbn = is.readUTF();
BookInfo info = new BookInfo(isbn);
info.id = id;
info.title = is.readUTF();
info.ranking = is.readInt();
info.reviews = is.readInt();
info.lastRanking = is.readInt();
info.lastReviews = is.readInt();
return info;
}
// Adds an entry to the store or modifies the existing
// entry if a matching ISBN exists.
public void saveBookInfo(BookInfo bookInfo)
throws IOException, RecordStoreException {
if (store != null) {
searchISBN = bookInfo.getIsbn();
RecordEnumeration e = store.enumerateRecords(
this, null, false);
if (e.numRecords() > 0) {
// A matching record exists. Set the id
// of the BookInfo to match the existing record
bookInfo.id = e.nextRecordId();
byte[] bytes = toByteArray(bookInfo);
store.setRecord(bookInfo.id, bytes, 0, bytes.length);
} else {
// Create a new record
bookInfo.id = store.getNextRecordID();
byte[] bytes = toByteArray(bookInfo);
store.addRecord(bytes, 0, bytes.length);
}
// Finally, destroy the RecordEnumeration
e.destroy();
}
}
// Deletes the entry for a book from the store
public void deleteBook(BookInfo bookInfo) throws RecordStoreException {
if (store != null) {
store.deleteRecord(bookInfo.id);
}
}
// RecordComparator implementation
public int compare(byte[] book1, byte[] book2) {
try {
DataInputStream stream1 =
new DataInputStream(new ByteArrayInputStream(book1));
DataInputStream stream2 =
new DataInputStream(new ByteArrayInputStream(book2));
// Match based on the ISBN, but sort based on the title.
String isbn1 = stream1.readUTF();
String isbn2 = stream2.readUTF();
if (isbn1.equals(isbn2)) {
return RecordComparator.EQUIVALENT;
}
String title1 = stream1.readUTF();
String title2 = stream2.readUTF();
int result = title1.rupareTo(title2);
if (result == 0) {
return RecordComparator.EQUIVALENT;
}
return result < 0 ? RecordComparator.PRECEDES :
RecordComparator.FOLLOWS;
} catch (IOException ex) {
return RecordComparator.EQUIVALENT;
}
}
// RecordFilter implementation
public boolean matches(byte[] book) {
if (searchISBN != null) {
try {
DataInputStream stream =
new DataInputStream(new ByteArrayInputStream(book));
// Match based on the ISBN.
return searchISBN.equals(stream.readUTF());
} catch (IOException ex) {
System.err.println(ex);
}
}
// Default is not to match
return false;
}
// Writes a record into a byte array.
private byte[] toByteArray(BookInfo bookInfo) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream os = new DataOutputStream(baos);
os.writeUTF(bookInfo.isbn);
os.writeUTF(bookInfo.title == null ? "" : bookInfo.title);
os.writeInt(bookInfo.ranking);
os.writeInt(bookInfo.reviews);
os.writeInt(bookInfo.lastRanking);
os.writeInt(bookInfo.lastReviews);
return baos.toByteArray();
}
}
/**
* A class that represents a book listing
* at an online book set, including the number
* of reviews for the book and its sales ranking.
*/
class BookInfo {
int id; // Used when persisting
String isbn; // The book ISBN
String title; // The book title
int reviews; // Number of reviews
int ranking; // Current ranking
int lastReviews; // Last review count
int lastRanking; // Last ranking
public BookInfo(String isbn) {
this.isbn = isbn;
}
public String getIsbn() {
return isbn;
}
public String getTitle() {
return title;
}
public int getReviews() {
return reviews;
}
public int getRanking() {
return ranking;
}
public int getLastReviews() {
return lastReviews;
}
public int getLastRanking() {
return lastRanking;
}
// Installs details parsed from an input stream
public void setFromInputStream(InputStream is) {
// Use an InputHelper to search the input
InputHelper helper = new InputHelper(is);
try {
// Default new values to current values
int newRanking = this.ranking;
int newReviews = this.reviews;
boolean found = helper.moveAfterString("buying info: ");
if (!found) {
return;
}
// Gather the title from the rest of this line
StringBuffer titleBuffer = helper.getRestOfLine();
// Look for the number of reviews
found = helper.moveAfterString("Based on ");
if (!found) {
return;
}
// Gather the number of reviews from the current location
String reviewString = helper.gatherNumber();
// Look for the sales rank
found = helper.moveAfterString("Sales Rank: ");
if (!found) {
return;
}
// Gather the number from the current location
String rankingString = helper.gatherNumber();
// Having safely found everything, set the new title
title = titleBuffer.toString().trim();
// Now convert the reviews and ranking to integers.
// If they fail to convert, just leave the existing
// values.
try {
newRanking = Integer.parseInt(rankingString);
} catch (NumberFormatException ex) {
}
if (newRanking != ranking) {
lastRanking = ranking;
ranking = newRanking;
if (lastRanking == 0) {
// First time, set last and current
// to the same value
lastRanking = ranking;
}
}
try {
newReviews = Integer.parseInt(reviewString);
} catch (NumberFormatException ex) {
}
if (newReviews != reviews) {
lastReviews = reviews;
reviews = newReviews;
if (lastReviews == 0) {
// First time, set last and current
// to the same value
lastReviews = reviews;
}
}
} catch (IOException ex) {
} finally {
// Allow garbage collection
helper.dispose();
helper = null;
}
}
}
// A class that scans through an input
// stream for strins without reading the
// entire stream into a large string.
class InputHelper {
// Size of the input buffer
private static final int BUFFER_SIZE = 1024;
// The input buffer
private final char[] buffer = new char[BUFFER_SIZE];
// Number of characters left in the buffer
private int charsLeft;
// Index of the next character in the buffer
private int nextChar;
// InputStreamReader used to map to Unicode
private InputStreamReader reader;
// Constructs a helper to read a given stream
public InputHelper(InputStream is) {
reader = new InputStreamReader(is);
}
// Cleans up when no longer needed
public void dispose() {
if (reader != null) {
try {
reader.close();
} catch (IOException ex) {
}
reader = null;
}
}
// Looks for a given string in the input
// stream and positions the stream so that the
// next character read is one beyond the string.
// Returns true if the string was found, false if
// not (and the stream will have been completely read).
public boolean moveAfterString(String str) throws IOException {
char[] chars = str.toCharArray();
int count = chars.length;
char firstChar = chars[0];
char c = (char)0;
for (;;) {
if (c != firstChar && !findNext(firstChar)) {
// Reached the end of the input stream
return false;
}
boolean mismatch = false;
for (int i = 1; i < count; i++) {
c = getNext();
if (c != chars[i]) {
mismatch = true;
break;
}
}
if (!mismatch) {
return true;
}
// Mismatch. "c" has the first mismatched
// character - start the loop again with
// that character. This is necessary because we
// could have found "wweb" while looking for "web"
}
}
// Gets the characters for a number, ignoring
// the grouping separator. The number starts at the
// current input position, but any leading non-numerics
// are skipped.
public String gatherNumber() throws IOException {
StringBuffer sb = new StringBuffer();
boolean gotNumeric = false;
for (;;) {
char c = getNext();
// Skip until we find a digit.
boolean isDigit = Character.isDigit(c);
if (!gotNumeric && !isDigit) {
continue;
}
gotNumeric = true;
if (!isDigit) {
if (c == "." || c == ",") {
continue;
}
break;
}
sb.append(c);
}
return sb.toString();
}
// Gets the balance of the current line
// and returns it as a StringBuffer
public StringBuffer getRestOfLine() throws IOException {
StringBuffer sb = new StringBuffer();
char c;
for (;;) {
c = getNext();
if (c == "\n" || c == (char)0) {
break;
}
sb.append(c);
}
return sb;
}
// Gets the next character from the stream,
// returning (char)0 when all input has been read.
private char getNext() throws IOException {
if (charsLeft == 0) {
charsLeft = reader.read(buffer, 0, BUFFER_SIZE);
if (charsLeft < 0) {
return (char)0;
}
nextChar = 0;
}
charsLeft--;
return buffer[nextChar++];
}
// Finds the next instance of a given character in the
// input stream. The input stream is positioned after
// the located character. If EOF is reached without
// finding the character, false is returned.
private boolean findNext(char c) throws IOException {
for (;;) {
if (charsLeft == 0) {
charsLeft = reader.read(buffer, 0, BUFFER_SIZE);
if (charsLeft < 0) {
return false;
}
nextChar = 0;
}
charsLeft--;
if (c == buffer[nextChar++]) {
return true;
}
}
}
}
Read and write to the record store.
/*--------------------------------------------------
* ReadWrite.java
*
* Read and write to the record store.
*
* No GUI interface, all output is to the console
*
* Example from the book: Core J2ME Technology
* Copyright John W. Muchow http://www.CoreJ2ME.ru
* You may use/modify for any non-commercial purpose
*-------------------------------------------------*/
import javax.microedition.rms.*;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;
public class ReadWrite extends MIDlet
{
private RecordStore rs = null;
static final String REC_STORE = "db_1";
public ReadWrite()
{
openRecStore(); // Create the record store
// Write a few records and read them back
writeRecord("J2ME and MIDP");
writeRecord("Wireless Technology");
readRecords();
closeRecStore(); // Close record store
deleteRecStore(); // Remove the record store
}
public void destroyApp( boolean unconditional )
{
}
public void startApp()
{
// There is no user interface, go ahead and shutdown
destroyApp(false);
notifyDestroyed();
}
public void pauseApp()
{
}
public void openRecStore()
{
try
{
// The second parameter indicates that the record store
// should be created if it does not exist
rs = RecordStore.openRecordStore(REC_STORE, true );
}
catch (Exception e)
{
db(e.toString());
}
}
public void closeRecStore()
{
try
{
rs.closeRecordStore();
}
catch (Exception e)
{
db(e.toString());
}
}
public void deleteRecStore()
{
if (RecordStore.listRecordStores() != null)
{
try
{
RecordStore.deleteRecordStore(REC_STORE);
}
catch (Exception e)
{
db(e.toString());
}
}
}
public void writeRecord(String str)
{
byte[] rec = str.getBytes();
try
{
rs.addRecord(rec, 0, rec.length);
}
catch (Exception e)
{
db(e.toString());
}
}
public void readRecords()
{
try
{
// Intentionally make this too small to test code below
byte[] recData = new byte[5];
int len;
for (int i = 1; i <= rs.getNumRecords(); i++)
{
if (rs.getRecordSize(i) > recData.length)
recData = new byte[rs.getRecordSize(i)];
len = rs.getRecord(i, recData, 0);
System.out.println("Record #" + i + ": " + new String(recData, 0, len));
System.out.println("------------------------------");
}
}
catch (Exception e)
{
db(e.toString());
}
}
/*--------------------------------------------------
* Simple message to console for debug/errors
* When used with Exceptions we should handle the
* error in a more appropriate manner.
*-------------------------------------------------*/
private void db(String str)
{
System.err.println("Msg: " + str);
}
}
Record Enumeration Example
/*
J2ME: The Complete Reference
James Keogh
Publisher: McGraw-Hill
ISBN 0072227109
*/
//jad file (please verify the jar size)
/*
MIDlet-Name: RecordEnumerationExample
MIDlet-Version: 1.0
MIDlet-Vendor: MyCompany
MIDlet-Jar-URL: RecordEnumerationExample.jar
MIDlet-1: RecordEnumerationExample, , RecordEnumerationExample
MicroEdition-Configuration: CLDC-1.0
MicroEdition-Profile: MIDP-1.0
MIDlet-JAR-SIZE: 100
*/
import javax.microedition.rms.*;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import java.io.*;
public class RecordEnumerationExample
extends MIDlet implements CommandListener
{
private Display display;
private Alert alert;
private Form form;
private Command exit;
private Command start;
private RecordStore recordstore = null;
private RecordEnumeration recordEnumeration = null;
public RecordEnumerationExample ()
{
display = Display.getDisplay(this);
exit = new Command("Exit", Command.SCREEN, 1);
start = new Command("Start", Command.SCREEN, 1);
form = new Form("RecordEnumeration");
form.addCommand(exit);
form.addCommand(start);
form.setCommandListener(this);
}
public void startApp()
{
display.setCurrent(form);
}
public void pauseApp()
{
}
public void destroyApp( boolean unconditional )
{
}
public void commandAction(Command command,
Displayable displayable)
{
if (command == exit)
{
destroyApp(true);
notifyDestroyed();
}
else if (command == start)
{
try
{
recordstore = RecordStore.openRecordStore(
"myRecordStore", true );
}
catch (Exception error)
{
alert = new Alert("Error Creating",
error.toString(), null, AlertType.WARNING);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert);
}
try
{
String outputData[] = {"First Record",
"Second Record", "Third Record"};
for (int x = 0; x < 3; x++)
{
byte[] byteOutputData = outputData[x].getBytes();
recordstore.addRecord(byteOutputData,
0, byteOutputData.length);
}
}
catch ( Exception error)
{
alert = new Alert("Error Writing",
error.toString(), null, AlertType.WARNING);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert);
}
try
{
StringBuffer buffer = new StringBuffer();
recordEnumeration =
recordstore.enumerateRecords(null, null, false);
while (recordEnumeration.hasNextElement())
{
buffer.append(new String(recordEnumeration.nextRecord()));
buffer.append("\n");
}
alert = new Alert("Reading",
buffer.toString(), null, AlertType.WARNING);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert);
}
catch (Exception error)
{
alert = new Alert("Error Reading",
error.toString(), null, AlertType.WARNING);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert);
}
try
{
recordstore.closeRecordStore();
}
catch (Exception error)
{
alert = new Alert("Error Closing",
error.toString(), null, AlertType.WARNING);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert);
}
if (RecordStore.listRecordStores() != null)
{
try
{
RecordStore.deleteRecordStore("myRecordStore");
recordEnumeration.destroy();
}
catch (Exception error)
{
alert = new Alert("Error Removing",
error.toString(), null, AlertType.WARNING);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert);
}
}
}
}
}
Record MIDlet
/*
* Wireless Java 2nd edition Jonathan Knudsen Publisher: Apress ISBN: 1590590775
*/
import java.util.Enumeration;
import java.util.Hashtable;
import javax.microedition.lcdui.rumand;
import javax.microedition.lcdui.rumandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.StringItem;
import javax.microedition.lcdui.TextField;
import javax.microedition.midlet.MIDlet;
import javax.microedition.rms.RecordEnumeration;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreException;
public class RecordMIDlet extends MIDlet implements CommandListener {
private static final String kUser = "user";
private static final String kPassword = "password";
private Preferences mPreferences;
private Form mForm;
private TextField mUserField, mPasswordField;
public RecordMIDlet() {
try {
mPreferences = new Preferences("preferences");
} catch (RecordStoreException rse) {
mForm = new Form("Exception");
mForm.append(new StringItem(null, rse.toString()));
mForm.addCommand(new Command("Exit", Command.EXIT, 0));
mForm.setCommandListener(this);
return;
}
mForm = new Form("Login");
mUserField = new TextField("Name", mPreferences.get(kUser), 32, 0);
mPasswordField = new TextField("Password", mPreferences.get(kPassword),
32, 0);
mForm.append(mUserField);
mForm.append(mPasswordField);
mForm.addCommand(new Command("Exit", Command.EXIT, 0));
mForm.setCommandListener(this);
}
public void startApp() {
Display.getDisplay(this).setCurrent(mForm);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
// Save the user name and password.
mPreferences.put(kUser, mUserField.getString());
mPreferences.put(kPassword, mPasswordField.getString());
try {
mPreferences.save();
} catch (RecordStoreException rse) {
}
}
public void commandAction(Command c, Displayable s) {
if (c.getCommandType() == Command.EXIT) {
destroyApp(true);
notifyDestroyed();
}
}
}
class Preferences {
private String mRecordStoreName;
private Hashtable mHashtable;
public Preferences(String recordStoreName) throws RecordStoreException {
mRecordStoreName = recordStoreName;
mHashtable = new Hashtable();
load();
}
public String get(String key) {
return (String) mHashtable.get(key);
}
public void put(String key, String value) {
if (value == null)
value = "";
mHashtable.put(key, value);
}
private void load() throws RecordStoreException {
RecordStore rs = null;
RecordEnumeration re = null;
try {
rs = RecordStore.openRecordStore(mRecordStoreName, true);
re = rs.enumerateRecords(null, null, false);
while (re.hasNextElement()) {
byte[] raw = re.nextRecord();
String pref = new String(raw);
// Parse out the name.
int index = pref.indexOf("|");
String name = pref.substring(0, index);
String value = pref.substring(index + 1);
put(name, value);
}
} finally {
if (re != null)
re.destroy();
if (rs != null)
rs.closeRecordStore();
}
}
public void save() throws RecordStoreException {
RecordStore rs = null;
RecordEnumeration re = null;
try {
rs = RecordStore.openRecordStore(mRecordStoreName, true);
re = rs.enumerateRecords(null, null, false);
// First remove all records, a little clumsy.
while (re.hasNextElement()) {
int id = re.nextRecordId();
rs.deleteRecord(id);
}
// Now save the preferences records.
Enumeration keys = mHashtable.keys();
while (keys.hasMoreElements()) {
String key = (String) keys.nextElement();
String value = get(key);
String pref = key + "|" + value;
byte[] raw = pref.getBytes();
rs.addRecord(raw, 0, raw.length);
}
} finally {
if (re != null)
re.destroy();
if (rs != null)
rs.closeRecordStore();
}
}
}
Search Example
/*
J2ME: The Complete Reference
James Keogh
Publisher: McGraw-Hill
ISBN 0072227109
*/
// jad file (Please verify the jar size first)
/*
MIDlet-Name: SearchExample
MIDlet-Version: 1.0
MIDlet-Vendor: MyCompany
MIDlet-Jar-URL: SearchExample.jar
MIDlet-1: SearchExample, , SearchExample
MicroEdition-Configuration: CLDC-1.0
MicroEdition-Profile: MIDP-1.0
MIDlet-JAR-SIZE: 100
*/
import javax.microedition.rms.*;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import java.io.*;
public class SearchExample extends MIDlet implements CommandListener
{
private Display display;
private Alert alert;
private Form form;
private Command exit;
private Command start;
private RecordStore recordstore = null;
private RecordEnumeration recordEnumeration = null;
private Filter filter = null;
public SearchExample ()
{
display = Display.getDisplay(this);
exit = new Command("Exit", Command.SCREEN, 1);
start = new Command("Start", Command.SCREEN, 1);
form = new Form("Mixed RecordEnumeration", null);
form.addCommand(exit);
form.addCommand(start);
form.setCommandListener(this);
}
public void startApp()
{
display.setCurrent(form);
}
public void pauseApp()
{
}
public void destroyApp( boolean unconditional )
{
}
public void commandAction(Command command, Displayable displayable)
{
if (command == exit)
{
destroyApp(true);
notifyDestroyed();
}
else if (command == start)
{
try
{
recordstore = RecordStore.openRecordStore(
"myRecordStore", true );
}
catch (Exception error)
{
alert = new Alert("Error Creating",
error.toString(), null, AlertType.WARNING);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert);
}
try
{
String outputData[] = {"Mary", "Bob", "Adam"};
for (int x = 0 ; x < 3; x++)
{
byte[] byteOutputData = outputData[x].getBytes();
recordstore.addRecord(byteOutputData, 0,
byteOutputData.length);
}
}
catch ( Exception error)
{
alert = new Alert("Error Writing",
error.toString(), null, AlertType.WARNING);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert);
}
try
{
filter = new Filter("Bob");
recordEnumeration = recordstore.enumerateRecords(
filter, null, false);
if (recordEnumeration.numRecords() > 0)
{
String string = new String(recordEnumeration.nextRecord());
alert = new Alert("Reading", string,
null, AlertType.WARNING);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert);
}
}
catch (Exception error)
{
alert = new Alert("Error Reading",
error.toString(), null, AlertType.WARNING);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert);
}
try
{
recordstore.closeRecordStore();
}
catch (Exception error)
{
alert = new Alert("Error Closing",
error.toString(), null, AlertType.WARNING);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert);
}
if (RecordStore.listRecordStores() != null)
{
try
{
RecordStore.deleteRecordStore("myRecordStore");
recordEnumeration.destroy();
filter.filterClose();
}
catch (Exception error)
{
alert = new Alert("Error Removing",
error.toString(), null, AlertType.WARNING);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert);
}
}
}
}
}
class Filter implements RecordFilter
{
private String search = null;
private ByteArrayInputStream inputstream = null;
private DataInputStream datainputstream = null;
public Filter(String search)
{
this.search = search.toLowerCase();
}
public boolean matches(byte[] suspect)
{
String string = new String(suspect).toLowerCase();
if (string!= null && string.indexOf(search) != -1)
return true;
else
return false;
}
public void filterClose()
{
try
{
if (inputstream != null)
{
inputstream.close();
}
if (datainputstream != null)
{
datainputstream.close();
}
}
catch ( Exception error)
{
}
}
}
Search Mixed Record Data Type Example
/*
J2ME: The Complete Reference
James Keogh
Publisher: McGraw-Hill
ISBN 0072227109
*/
// jad file (Please verify the jar size first)
/*
MIDlet-Name: SearchMixedRecordDataTypeExample
MIDlet-Version: 1.0
MIDlet-Vendor: MyCompany
MIDlet-Jar-URL: SearchMixedRecordDataTypeExample.jar
MIDlet-1: SearchMixedRecordDataTypeExample, ,
SearchMixedRecordDataTypeExample
MicroEdition-Configuration: CLDC-1.0
MicroEdition-Profile: MIDP-1.0
MIDlet-JAR-SIZE: 100
*/
import javax.microedition.rms.*;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import java.io.*;
public class SearchMixedRecordDataTypeExample
extends MIDlet implements CommandListener
{
private Display display;
private Alert alert;
private Form form;
private Command exit;
private Command start;
private RecordStore recordstore = null;
private RecordEnumeration recordEnumeration = null;
private Filter filter = null;
public SearchMixedRecordDataTypeExample ()
{
display = Display.getDisplay(this);
exit = new Command("Exit", Command.SCREEN, 1);
start = new Command("Start", Command.SCREEN, 1);
form = new Form("Mixed RecordEnumeration");
form.addCommand(exit);
form.addCommand(start);
form.setCommandListener(this);
}
public void startApp()
{
display.setCurrent(form);
}
public void pauseApp()
{
}
public void destroyApp( boolean unconditional )
{
}
public void commandAction(Command command, Displayable displayable)
{
if (command == exit)
{
destroyApp(true);
notifyDestroyed();
}
else if (command == start)
{
try
{
recordstore = RecordStore.openRecordStore(
"myRecordStore", true );
}
catch (Exception error)
{
alert = new Alert("Error Creating",
error.toString(), null, AlertType.WARNING);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert);
}
try
{
byte[] outputRecord;
String outputString[] = {"Adam", "Bob", "Mary"};
int outputInteger[] = {15, 10, 5};
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
DataOutputStream outputDataStream =
new DataOutputStream(outputStream);
for (int x = 0; x < 3; x++)
{
outputDataStream.writeUTF(outputString[x]);
outputDataStream.writeInt(outputInteger[x]);
outputDataStream.flush();
outputRecord = outputStream.toByteArray();
recordstore.addRecord(outputRecord, 0, outputRecord.length);
outputStream.reset();
}
outputStream.close();
outputDataStream.close();
}
catch ( Exception error)
{
alert = new Alert("Error Writing",
error.toString(), null, AlertType.WARNING);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert);
}
try
{
String inputString;
byte[] byteInputData = new byte[300];
ByteArrayInputStream inputStream =
new ByteArrayInputStream(byteInputData);
DataInputStream inputDataStream =
new DataInputStream(inputStream);
if (recordstore.getNumRecords() > 0)
{
filter = new Filter("Mary");
recordEnumeration = recordstore.enumerateRecords(
filter, null, false);
while (recordEnumeration.hasNextElement())
{
recordstore.getRecord(recordEnumeration.nextRecordId(),
byteInputData, 0);
inputString = inputDataStream.readUTF() +
" " + inputDataStream.readInt();
alert = new Alert("Reading", inputString,
null, AlertType.WARNING);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert);
}
}
inputStream.close();
}
catch (Exception error)
{
alert = new Alert("Error Reading",
error.toString(), null, AlertType.WARNING);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert);
}
try
{
recordstore.closeRecordStore();
}
catch (Exception error)
{
alert = new Alert("Error Closing",
error.toString(), null, AlertType.WARNING);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert);
}
if (RecordStore.listRecordStores() != null)
{
try
{
RecordStore.deleteRecordStore("myRecordStore");
filter.filterClose();
recordEnumeration.destroy();
}
catch (Exception error)
{
alert = new Alert("Error Removing",
error.toString(), null, AlertType.WARNING);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert);
}
}
}
}
}
class Filter implements RecordFilter
{
private String search = null;
private ByteArrayInputStream inputstream = null;
private DataInputStream datainputstream = null;
public Filter(String searchcriteria)
{
search = searchcriteria;
}
public boolean matches(byte[] suspect)
{
String string = null;
try
{
inputstream = new ByteArrayInputStream(suspect);
datainputstream = new DataInputStream(inputstream);
string = datainputstream.readUTF();
}
catch (Exception error)
{
return false;
}
if (string!= null && string.indexOf(search) != -1)
return true;
else
return false;
}
public void filterClose()
{
try
{
if (inputstream != null)
{
inputstream.close();
}
if (datainputstream != null)
{
datainputstream.close();
}
}
catch (Exception error)
{
}
}
}
Sort Mixed Record Data Type Example
/*
J2ME: The Complete Reference
James Keogh
Publisher: McGraw-Hill
ISBN 0072227109
*/
//jad file (please verify the jar size)
/*
MIDlet-Name: SortMixedRecordDataTypeExample
MIDlet-Version: 1.0
MIDlet-Vendor: MyCompany
MIDlet-Jar-URL: SortMixedRecordDataTypeExample.jar
MIDlet-1: SortMixedRecordDataTypeExample, ,
SortMixedRecordDataTypeExample
MicroEdition-Configuration: CLDC-1.0
MicroEdition-Profile: MIDP-1.0
MIDlet-JAR-SIZE: 100
*/
import javax.microedition.rms.*;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import java.io.*;
public class SortMixedRecordDataTypeExample
extends MIDlet implements CommandListener
{
private Display display;
private Alert alert;
private Form form;
private Command exit;
private Command start;
private RecordStore recordstore = null;
private RecordEnumeration recordEnumeration = null;
private Comparator comparator = null;
public SortMixedRecordDataTypeExample ()
{
display = Display.getDisplay(this);
exit = new Command("Exit", Command.SCREEN, 1);
start = new Command("Start", Command.SCREEN, 1);
form = new Form("Mixed RecordEnumeration");
form.addCommand(exit);
form.addCommand(start);
form.setCommandListener(this);
}
public void startApp()
{
display.setCurrent(form);
}
public void pauseApp()
{
}
public void destroyApp( boolean unconditional )
{
}
public void commandAction(Command command, Displayable displayable)
{
if (command == exit)
{
destroyApp(true);
notifyDestroyed();
}
else if (command == start)
{
try
{
recordstore = RecordStore.openRecordStore(
"myRecordStore", true );
}
catch (Exception error)
{
alert = new Alert("Error Creating",
error.toString(), null, AlertType.WARNING);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert);
}
try
{
byte[] outputRecord;
String outputString[] = {"Mary", "Bob", "Adam"};
int outputInteger[] = {15, 10, 5};
ByteArrayOutputStream outputStream =
new ByteArrayOutputStream();
DataOutputStream outputDataStream =
new DataOutputStream(outputStream);
for (int x = 0; x < 3; x++)
{
outputDataStream.writeUTF(outputString[x]);
outputDataStream.writeInt(outputInteger[x]);
outputDataStream.flush();
outputRecord = outputStream.toByteArray();
recordstore.addRecord(outputRecord, 0,
outputRecord.length);
outputStream.reset();
}
outputStream.close();
outputDataStream.close();
}
catch ( Exception error)
{
alert = new Alert("Error Writing",
error.toString(), null, AlertType.WARNING);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert);
}
try
{
String[] inputString = new String[3];
int z = 0;
byte[] byteInputData = new byte[300];
ByteArrayInputStream inputStream =
new ByteArrayInputStream(byteInputData);
DataInputStream inputDataStream =
new DataInputStream(inputStream);
StringBuffer buffer = new StringBuffer();
comparator = new Comparator();
recordEnumeration = recordstore.enumerateRecords(
null, comparator, false);
while (recordEnumeration.hasNextElement())
{
recordstore.getRecord( recordEnumeration.nextRecordId(),
byteInputData, 0);
buffer.append(inputDataStream.readUTF());
buffer.append(inputDataStream.readInt());
buffer.append("\n");
inputDataStream.reset();
}
alert = new Alert("Reading", buffer.toString(), null,
AlertType.WARNING);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert);
inputDataStream.close();
inputStream.close();
}
catch (Exception error)
{
alert = new Alert("Error Reading",
error.toString(), null, AlertType.WARNING);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert);
}
try
{
recordstore.closeRecordStore();
}
catch (Exception error)
{
alert = new Alert("Error Closing",
error.toString(), null, AlertType.WARNING);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert);
}
if (RecordStore.listRecordStores() != null)
{
try
{
RecordStore.deleteRecordStore("myRecordStore");
comparator.rupareClose();
recordEnumeration.destroy();
}
catch (Exception error)
{
alert = new Alert("Error Removing",
error.toString(), null, AlertType.WARNING);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert);
}
}
}
}
}
class Comparator implements RecordComparator
{
private byte[] comparatorInputData = new byte[300];
private ByteArrayInputStream comparatorInputStream = null;
private DataInputStream comparatorInputDataType = null;
public int compare(byte[] record1, byte[] record2)
{
int record1int, record2int;
try
{
int maxlen = Math.max(record1.length, record2.length);
if (maxlen > comparatorInputData.length)
{
comparatorInputData = new byte[maxlen];
}
comparatorInputStream = new ByteArrayInputStream(record1);
comparatorInputDataType =
new DataInputStream(comparatorInputStream);
comparatorInputDataType.readUTF();
record1int = comparatorInputDataType.readInt();
comparatorInputStream = new ByteArrayInputStream(record2);
comparatorInputDataType =
new DataInputStream(comparatorInputStream);
comparatorInputDataType.readUTF();
record2int = comparatorInputDataType.readInt();
if (record1int == record2int)
{
return RecordComparator.EQUIVALENT;
}
else if (record1int < record2int)
{
return RecordComparator.PRECEDES;
}
else
{
return RecordComparator.FOLLOWS;
}
}
catch (Exception error)
{
return RecordComparator.EQUIVALENT;
}
}
public void compareClose()
{
try
{
if (comparatorInputStream!= null)
{
comparatorInputStream.close();
}
if (comparatorInputDataType!= null)
{
comparatorInputDataType.close();
}
}
catch (Exception error)
{
}
}
}
Sort Record Example
/*
J2ME: The Complete Reference
James Keogh
Publisher: McGraw-Hill
ISBN 0072227109
*/
//jad file (please verify the jar size)
/*
MIDlet-Name: SortExample
MIDlet-Version: 1.0
MIDlet-Vendor: MyCompany
MIDlet-Jar-URL: SortExample.jar
MIDlet-1: SortExample, , SortExample
MicroEdition-Configuration: CLDC-1.0
MicroEdition-Profile: MIDP-1.0
MIDlet-JAR-SIZE: 100
*/
import javax.microedition.rms.*;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import java.io.*;
public class SortExample extends MIDlet implements CommandListener
{
private Display display;
private Alert alert;
private Form form;
private Command exit;
private Command start;
private RecordStore recordstore = null;
private RecordEnumeration recordEnumeration = null;
private Comparator comparator = null;
public SortExample ()
{
display = Display.getDisplay(this);
exit = new Command("Exit", Command.SCREEN, 1);
start = new Command("Start", Command.SCREEN, 1);
form = new Form("Mixed RecordEnumeration", null);
form.addCommand(exit);
form.addCommand(start);
form.setCommandListener(this);
}
public void startApp()
{
display.setCurrent(form);
}
public void pauseApp()
{
}
public void destroyApp( boolean unconditional )
{
}
public void commandAction(Command command, Displayable displayable)
{
if (command == exit)
{
destroyApp(true);
notifyDestroyed();
}
else if (command == start)
{
try
{
recordstore = RecordStore.openRecordStore(
"myRecordStore", true );
}
catch (Exception error)
{
alert = new Alert("Error Creating",
error.toString(), null, AlertType.WARNING);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert);
}
try
{
String outputData[] = {"Mary", "Bob", "Adam"};
for (int x = 0; x < 3; x++)
{
byte[] byteOutputData = outputData[x].getBytes();
recordstore.addRecord(byteOutputData, 0,
byteOutputData.length);
}
}
catch ( Exception error)
{
alert = new Alert("Error Writing",
error.toString(), null, AlertType.WARNING);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert);
}
try
{
StringBuffer buffer = new StringBuffer();
Comparator comparator = new Comparator();
recordEnumeration = recordstore.enumerateRecords(
null, comparator, false);
while (recordEnumeration.hasNextElement())
{
buffer.append(new String(recordEnumeration.nextRecord()));
buffer.append("\n");
}
alert = new Alert("Reading", buffer.toString() ,
null, AlertType.WARNING);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert);
}
catch (Exception error)
{
alert = new Alert("Error Reading",
error.toString(), null, AlertType.WARNING);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert);
}
try
{
recordstore.closeRecordStore();
}
catch (Exception error)
{
alert = new Alert("Error Closing",
error.toString(), null, AlertType.WARNING);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert);
}
if (RecordStore.listRecordStores() != null)
{
try
{
RecordStore.deleteRecordStore("myRecordStore");
recordEnumeration.destroy();
}
catch (Exception error)
{
alert = new Alert("Error Removing",
error.toString(), null, AlertType.WARNING);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert);
}
}
}
}
}
class Comparator implements RecordComparator
{
public int compare(byte[] record1, byte[] record2)
{
String string1 = new String(record1),
string2= new String(record2);
int comparison = string1.rupareTo(string2);
if (comparison == 0)
return RecordComparator.EQUIVALENT;
else if (comparison < 0)
return RecordComparator.PRECEDES;
else
return RecordComparator.FOLLOWS;
}
}
Store Database
/* License
*
* Copyright 1994-2004 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistribution in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed, licensed or intended
* for use in the design, construction, operation or maintenance of any
* nuclear facility.
*/
import java.io.*;
import javax.microedition.midlet.*;
import javax.microedition.rms.*;
public class TestStore extends MIDlet {
static final String DBNAME = "mydata";
public TestStore() {
RecordStore rs = null;
// Data is persistent across MIDlet invocations.
// So, first clear out the old record store...
try {
RecordStore.deleteRecordStore( DBNAME );
}
catch( Exception e ){
// ignore any errors...
}
// Now create a new one and dump
// each element out....
try {
rs = RecordStore.openRecordStore( DBNAME,
true );
byte[] data1 = "Here is the first record".getBytes();
byte[] data2 = "And here is the second".getBytes();
byte[] data3 = "And then the third".getBytes();
data3[0] = 0;
data3[data3.length-1] = (byte) -1;
rs.addRecord( data1, 0, data1.length );
rs.addRecord( data2, 0, data2.length );
rs.addRecord( data3, 0, data3.length );
dumpRecordStore( rs, System.out );
rs.closeRecordStore();
}
catch( RecordStoreException e ){
System.out.println( e );
}
notifyDestroyed();
}
public void dumpRecordStore( RecordStore rs,
PrintStream out )
{
if( rs == null ) return;
StringBuffer hexLine = new StringBuffer();
StringBuffer charLine = new StringBuffer();
try {
int lastID = rs.getNextRecordID();
byte[] data = new byte[100];
int size;
for( int i = 1; i < lastID; ++i ){
try {
size = rs.getRecordSize( i );
if( size > data.length ){
data = new byte[ size * 2 ];
}
out.println( "Record " + i +
" of size " + size );
rs.getRecord( i, data, 0 );
dumpRecord( data, size, out,
hexLine, charLine, 16 );
out.println( "" );
}
catch( InvalidRecordIDException e ){
continue;
}
}
}
catch( RecordStoreException e ){
out.println( "Exception reading record store: " + e );
}
}
private void dumpRecord( byte[] data, int size,
PrintStream out,
StringBuffer hexLine,
StringBuffer charLine,
int maxLen )
{
if( size == 0 ) return;
hexLine.setLength( 0 );
charLine.setLength( 0 );
int count = 0;
for( int i = 0; i < size; ++i ){
char b = (char) ( data[i] & 0xFF );
if( b < 0x10 ){
hexLine.append( "0" );
}
hexLine.append( Integer.toHexString( b ) );
hexLine.append( " " );
if( ( b >= 32 && b <= 127 ) ||
Character.isDigit( b ) ||
Character.isLowerCase( b ) ||
Character.isUpperCase( b ) ){
charLine.append( (char) b );
} else {
charLine.append( "." );
}
if( ++count >= maxLen || i == size-1 ){
while( count++ < maxLen ){
hexLine.append( " " );
}
hexLine.append( " " );
hexLine.append( charLine.toString() );
out.println( hexLine.toString() );
hexLine.setLength( 0 );
charLine.setLength( 0 );
count = 0;
}
}
}
public void destroyApp( boolean unconditional ) {
}
public void startApp() {
}
public void pauseApp() {
}
}
Test the RMS listener methods
/*--------------------------------------------------
* RmsListener.java
*
* Test the RMS listener methods
*
* No GUI interface, all output is to the console
*
* Example from the book: Core J2ME Technology
* Copyright John W. Muchow http://www.CoreJ2ME.ru
* You may use/modify for any non-commercial purpose
*-------------------------------------------------*/
import java.io.*;
import javax.microedition.midlet.*;
import javax.microedition.rms.*;
public class RmsListener extends MIDlet
{
private RecordStore rs = null;
static final String REC_STORE = "db_8";
public RmsListener()
{
// Open record store and add listener
openRecStore();
rs.addRecordListener(new TestRecordListener());
// Initiate actions that will wake up the listener
writeRecord("J2ME and MIDP");
updateRecord("MIDP and J2ME");
deleteRecord();
closeRecStore(); // Close record store
deleteRecStore(); // Remove the record store
}
public void destroyApp( boolean unconditional )
{
}
public void startApp()
{
// There is no user interface, go ahead and shutdown
destroyApp(false);
notifyDestroyed();
}
public void pauseApp()
{
}
public void openRecStore()
{
try
{
// The second parameter indicates that the record store
// should be created if it does not exist
rs = RecordStore.openRecordStore(REC_STORE, true);
}
catch (Exception e)
{
db(e.toString());
}
}
public void closeRecStore()
{
try
{
rs.closeRecordStore();
}
catch (Exception e)
{
db(e.toString());
}
}
public void deleteRecStore()
{
if (RecordStore.listRecordStores() != null)
{
try
{
RecordStore.deleteRecordStore(REC_STORE);
}
catch (Exception e)
{
db(e.toString());
}
}
}
public void writeRecord(String str)
{
byte[] rec = str.getBytes();
try
{
rs.addRecord(rec, 0, rec.length);
}
catch (Exception e)
{
db(e.toString());
}
}
public void updateRecord(String str)
{
try
{
rs.setRecord(1, str.getBytes(), 0, str.length());
}
catch (Exception e)
{
db(e.toString());
}
}
public void deleteRecord()
{
try
{
rs.deleteRecord(1);
}
catch (Exception e)
{
db(e.toString());
}
}
/*--------------------------------------------------
* Simple message to console for debug/errors
* When used with Exceptions we should handle the
* error in a more appropriate manner.
*-------------------------------------------------*/
public void db(String str)
{
System.err.println("Msg: " + str);
}
}
/*--------------------------------------------------
* Listen for updates to the record store
*-------------------------------------------------*/
class TestRecordListener implements RecordListener
{
public void recordAdded(RecordStore recordStore, int recordId)
{
try
{
System.out.println("Record with ID#: " + recordId +
" added to RecordStore: " + recordStore.getName());
}
catch (Exception e)
{
System.err.println(e);
}
}
public void recordDeleted(RecordStore recordStore, int recordId)
{
try
{
System.out.println("Record with ID#: " + recordId +
" deleted from RecordStore: " + recordStore.getName());
}
catch (Exception e)
{
System.err.println(e);
}
}
public void recordChanged(RecordStore recordStore, int recordId)
{
try
{
System.out.println("Record with ID#: " + recordId +
" changed in RecordStore: " + recordStore.getName());
}
catch (Exception e)
{
System.err.println(e);
}
}
}
Use streams to read and write Java data types to the record store.
/*--------------------------------------------------
* ReadWriteStreams.java
*
* Use streams to read and write Java data types
* to the record store.
*
* No GUI interface, all output is to the console
*
* Example from the book: Core J2ME Technology
* Copyright John W. Muchow http://www.CoreJ2ME.ru
* You may use/modify for any non-commercial purpose
*-------------------------------------------------*/
import java.io.*;
import javax.microedition.midlet.*;
import javax.microedition.rms.*;
public class ReadWriteStreams extends MIDlet
{
private RecordStore rs = null; // Record store
static final String REC_STORE = "db_1"; // Name of record store
public ReadWriteStreams()
{
openRecStore(); // Create the record store
writeTestData(); // Write a series of records
readStream(); // Read back the records
closeRecStore(); // Close record store
deleteRecStore(); // Remove the record store
}
public void destroyApp( boolean unconditional )
{
}
public void startApp()
{
// There is no user interface, go ahead and shutdown
destroyApp(false);
notifyDestroyed();
}
public void pauseApp()
{
}
public void openRecStore()
{
try
{
// The second parameter indicates that the record store
// should be created if it does not exist
rs = RecordStore.openRecordStore(REC_STORE, true );
}
catch (Exception e)
{
db(e.toString());
}
}
public void closeRecStore()
{
try
{
rs.closeRecordStore();
}
catch (Exception e)
{
db(e.toString());
}
}
public void deleteRecStore()
{
if (RecordStore.listRecordStores() != null)
{
try
{
RecordStore.deleteRecordStore(REC_STORE);
}
catch (Exception e)
{
db(e.toString());
}
}
}
/*--------------------------------------------------
* Create three arrays to write to record store
*-------------------------------------------------*/
public void writeTestData()
{
String[] strings = {"Text 1", "Text 2"};
boolean[] booleans = {false, true};
int[] integers = {1 , 2};
writeStream(strings, booleans, integers);
}
/*--------------------------------------------------
* Write to record store using streams.
*-------------------------------------------------*/
public void writeStream(String[] sData, boolean[] bData, int[] iData)
{
try
{
// Write data into an internal byte array
ByteArrayOutputStream strmBytes = new ByteArrayOutputStream();
// Write Java data types into the above byte array
DataOutputStream strmDataType = new DataOutputStream(strmBytes);
byte[] record;
for (int i = 0; i < sData.length; i++)
{
// Write Java data types
strmDataType.writeUTF(sData[i]);
strmDataType.writeBoolean(bData[i]);
strmDataType.writeInt(iData[i]);
// Clear any buffered data
strmDataType.flush();
// Get stream data into byte array and write record
record = strmBytes.toByteArray();
rs.addRecord(record, 0, record.length);
// Toss any data in the internal array so writes
// starts at beginning (of the internal array)
strmBytes.reset();
}
strmBytes.close();
strmDataType.close();
}
catch (Exception e)
{
db(e.toString());
}
}
/*--------------------------------------------------
* Read from the record store using streams
*-------------------------------------------------*/
public void readStream()
{
try
{
// Careful: Make sure this is big enough!
// Better yet, test and reallocate if necessary
byte[] recData = new byte[50];
// Read from the specified byte array
ByteArrayInputStream strmBytes = new ByteArrayInputStream(recData);
// Read Java data types from the above byte array
DataInputStream strmDataType = new DataInputStream(strmBytes);
for (int i = 1; i <= rs.getNumRecords(); i++)
{
// Get data into the byte array
rs.getRecord(i, recData, 0);
// Read back the data types
System.out.println("Record #" + i);
System.out.println("UTF: " + strmDataType.readUTF());
System.out.println("Boolean: " + strmDataType.readBoolean());
System.out.println("Int: " + strmDataType.readInt());
System.out.println("--------------------");
// Reset so read starts at beginning of array
strmBytes.reset();
}
strmBytes.close();
strmDataType.close();
}
catch (Exception e)
{
db(e.toString());
}
}
/*--------------------------------------------------
* Simple message to console for debug/errors
* When used with Exceptions we should handle the
* error in a more appropriate manner.
*-------------------------------------------------*/
private void db(String str)
{
System.err.println("Msg: " + str);
}
}
Write Read Mixed Data Types Example
/*
J2ME: The Complete Reference
James Keogh
Publisher: McGraw-Hill
ISBN 0072227109
*/
//jad file (please verify the jar size)
/*
MIDlet-Name: WriteReadMixedDataTypesExample
MIDlet-Version: 1.0
MIDlet-Vendor: MyCompany
MIDlet-Jar-URL: WriteReadMixedDataTypesExample.jar
MIDlet-1: WriteReadMixedDataTypesExample, ,
WriteReadMixedDataTypesExample
MicroEdition-Configuration: CLDC-1.0
MicroEdition-Profile: MIDP-1.0
MIDlet-JAR-SIZE: 100
*/
import javax.microedition.rms.*;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import java.io.*;
public class WriteReadMixedDataTypesExample
extends MIDlet implements CommandListener
{
private Display display;
private Alert alert;
private Form form;
private Command exit;
private Command start;
private RecordStore recordstore = null;
public WriteReadMixedDataTypesExample ()
{
display = Display.getDisplay(this);
exit = new Command("Exit", Command.SCREEN, 1);
start = new Command("Start", Command.SCREEN, 1);
form = new Form("Mixed Record");
form.addCommand(exit);
form.addCommand(start);
form.setCommandListener(this);
}
public void startApp()
{
display.setCurrent(form);
}
public void pauseApp()
{
}
public void destroyApp( boolean unconditional )
{
}
public void commandAction(Command command, Displayable displayable)
{
if (command == exit)
{
destroyApp(true);
notifyDestroyed();
}
else if (command == start)
{
try
{
recordstore = RecordStore.openRecordStore(
"myRecordStore", true );
}
catch (Exception error)
{
alert = new Alert("Error Creating",
error.toString(), null, AlertType.WARNING);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert);
}
try
{
byte[] outputRecord;
String outputString = "First Record";
int outputInteger = 15;
boolean outputBoolean = true;
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
DataOutputStream outputDataStream =
new DataOutputStream(outputStream);
outputDataStream.writeUTF(outputString);
outputDataStream.writeBoolean(outputBoolean);
outputDataStream.writeInt(outputInteger);
outputDataStream.flush();
outputRecord = outputStream.toByteArray();
recordstore.addRecord(outputRecord, 0, outputRecord.length);
outputStream.reset();
outputStream.close();
outputDataStream.close();
}
catch ( Exception error)
{
alert = new Alert("Error Writing",
error.toString(), null, AlertType.WARNING);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert);
}
try
{
String inputString = null;
int inputInteger = 0;
boolean inputBoolean = false;
byte[] byteInputData = new byte[100];
ByteArrayInputStream inputStream = new ByteArrayInputStream(byteInputData);
DataInputStream inputDataStream =
new DataInputStream(inputStream);
for (int x = 1; x <= recordstore.getNumRecords(); x++)
{
recordstore.getRecord(x, byteInputData, 0);
inputString = inputDataStream.readUTF();
inputBoolean = inputDataStream.readBoolean();
inputInteger = inputDataStream.readInt();
inputStream.reset();
}
inputStream.close();
inputDataStream.close();
alert = new Alert("Reading", inputString + " " +
inputInteger + " " +
inputBoolean, null, AlertType.WARNING);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert);
}
catch (Exception error)
{
alert = new Alert("Error Reading",
error.toString(), null, AlertType.WARNING);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert);
}
try
{
recordstore.closeRecordStore();
}
catch (Exception error)
{
alert = new Alert("Error Closing",
error.toString(), null, AlertType.WARNING);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert);
}
if (RecordStore.listRecordStores() != null)
{
try
{
RecordStore.deleteRecordStore("myRecordStore");
}
catch (Exception error)
{
alert = new Alert("Error Removing",
error.toString(), null, AlertType.WARNING);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert);
}
}
}
}
}