Java Tutorial/J2ME/RecordStore
Версия от 17:44, 31 мая 2010; (обсуждение)
Содержание
- 1 Add records to RecordStore
- 2 delete RecordStore
- 3 Filter Fields
- 4 Get record from RecordStore
- 5 Load yahoo stock quote
- 6 Mixed Record Enumeration
- 7 Read and write mixed data types with RecordStore
- 8 Record Enumeration
- 9 Record Monitor
- 10 RecordStore read and write
- 11 Retrieve All
- 12 Save data to RecordStore
- 13 Search Mixed Record Data Type
- 14 Search record in RecordStore
- 15 Sort Fields
- 16 Sort Mixed Record DataType
- 17 Sort records in RecordStore
Add records to RecordStore
import javax.microedition.lcdui.rumand;
import javax.microedition.lcdui.rumandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.TextBox;
import javax.microedition.lcdui.TextField;
import javax.microedition.midlet.MIDlet;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreNotFoundException;
public class addRecordMIDlet extends MIDlet implements CommandListener {
private Command exitCommand;
private Display display;
public addRecordMIDlet() {
display = Display.getDisplay(this);
exitCommand = new Command("exit", Command.SCREEN, 1);
}
public void startApp() {
TextBox aTextBox = new TextBox("a text", null, 256, TextField.ANY);
RecordStore rs = null;
byte[] nameEmail = null;
boolean existingOrNot = false;
boolean OK = true;
existingOrNot = existing("aRS");
if (existingOrNot) {
try {
rs = RecordStore.openRecordStore("aRS", false);
} catch (Exception e) {
OK = false;
} finally {
if (OK) {
aTextBox.setString("aRS Opened");
} else {
aTextBox.setString("aRS cannot open");
}
}
} else {
try {
rs = RecordStore.openRecordStore("aRS", true);
} catch (Exception e) {
OK = false;
} finally {
if (OK) {
aTextBox.setString("Ok");
} else {
aTextBox.setString("not ok");
}
}
}
if (OK)
try {
nameEmail = "login@yourname.net".getBytes();
rs.addRecord(nameEmail, 0, nameEmail.length);
aTextBox.setString("Added");
} catch (Exception e) {
aTextBox.setString("failed");
}
if (OK)
try {
rs.closeRecordStore();
} catch (Exception e) {
}
String result = new String(nameEmail);
int position = result.indexOf("=");
result = "Name:" + result.substring(0, position) + "\n" + "E-mail?"
+ result.substring(position + 1, result.length());
aTextBox.setString(result);
aTextBox.addCommand(exitCommand);
aTextBox.setCommandListener(this);
display.setCurrent(aTextBox);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
public boolean existing(String recordStoreName) {
boolean existingOrNot = false;
RecordStore rs = null;
if (recordStoreName.length() > 32)
return false;
try {
rs = RecordStore.openRecordStore(recordStoreName, false);
} catch (RecordStoreNotFoundException e) {
existingOrNot = false;
} catch (Exception e) {
} finally {
try {
rs.closeRecordStore();
} catch (Exception e) {
}
}
return existingOrNot;
}
public void commandAction(Command c, Displayable s) {
destroyApp(false);
notifyDestroyed();
}
}
delete RecordStore
import javax.microedition.lcdui.rumand;
import javax.microedition.lcdui.rumandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.TextBox;
import javax.microedition.lcdui.TextField;
import javax.microedition.midlet.MIDlet;
import javax.microedition.rms.RecordStore;
public class deleteRecordStoreMIDlet extends MIDlet implements CommandListener {
private Command exitCommand;
private Command confirmCommand;
private Display display;
public deleteRecordStoreMIDlet() {
display = Display.getDisplay(this);
exitCommand = new Command("exit", Command.EXIT, 1);
confirmCommand = new Command("confirm", Command.OK, 1);
}
public void startApp() {
TextBox aTextBox = new TextBox("RecordStore", null, 256, TextField.ANY);
aTextBox.addCommand(exitCommand);
aTextBox.addCommand(confirmCommand);
aTextBox.setCommandListener(this);
display.setCurrent(aTextBox);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
public void commandAction(Command c, Displayable s) {
if (c.getCommandType() == Command.EXIT) {
destroyApp(false);
notifyDestroyed();
} else {
try {
RecordStore.deleteRecordStore("aRS");
} catch (Exception e) {
}
}
}
}
Filter Fields
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import javax.microedition.lcdui.rumand;
import javax.microedition.lcdui.rumandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.TextBox;
import javax.microedition.lcdui.TextField;
import javax.microedition.midlet.MIDlet;
import javax.microedition.rms.RecordEnumeration;
import javax.microedition.rms.RecordFilter;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreNotFoundException;
public class FilterFieldsMIDlet extends MIDlet implements CommandListener {
private Command exitCommand;
private Display display;
private String[] names = { "A", "B", "C", "D" };
private int[] chineseScore = { 74, 98, 89, 76 };
private int[] englishScore = { 67, 89, 89, 78 };
private int[] mathScore = { 80, 76, 80, 78 };
public FilterFieldsMIDlet() {
display = Display.getDisplay(this);
exitCommand = new Command("Exit", Command.EXIT, 1);
}
public void startApp() {
TextBox aTextBox = new TextBox("Main", null, 256, TextField.ANY);
RecordStore rs = null;
byte[] nameEmail = null;
boolean existingOrNot = false;
boolean OK = true;
existingOrNot = existing("aRS3");
if (existingOrNot) {
try {
rs = RecordStore.openRecordStore("aRS3", false);
} catch (Exception e) {
OK = false;
} finally {
if (OK) {
aTextBox.setString("Ok");
} else {
aTextBox.setString("not tOk");
}
}
} else {
try {
rs = RecordStore.openRecordStore("aRS3", true);
} catch (Exception e) {
OK = false;
} finally {
if (OK) {
aTextBox.setString("Ok");
} else {
aTextBox.setString("Not Ok");
}
}
}
Student aStudent = null;
if (OK)
try {
for (int i = 0; i < names.length; i++) {
aStudent = new Student();
aStudent.write(names[i], chineseScore[i], englishScore[i], mathScore[i]);
byte[] data = aStudent.changeToByteArray();
int recordID = aStudent.getRecordID();
if (recordID != -1) {
rs.setRecord(recordID, data, 0, data.length);
} else {
recordID = rs.addRecord(data, 0, data.length);
aStudent.setRecordID(recordID);
}
aStudent = null;
}
aTextBox.setString("Added");
} catch (Exception e) {
aTextBox.setString("Failed");
}
String result = "";
aStudent = new Student();
if (OK)
try {
byte[] data;
int number = 0;
RecordFilter rf = new averageFilter();
RecordEnumeration re = rs.enumerateRecords(rf, null, false);
while (re.hasNextElement()) {
int recordID = re.nextRecordId();
data = rs.getRecord(recordID);
aStudent.changeFromByteArray(data);
result += recordID + "\n" + "Name:" + aStudent.getName() + "\n"
+ aStudent.getChineseScore() + "\n" + aStudent.getEnglishScore() + "\n"
+ aStudent.getMathScore() + "\n";
number++;
}
result += number;
aTextBox.setString(result);
} catch (Exception e) {
aTextBox.setString("Failed");
try {
rs.closeRecordStore();
System.out.println("1.Closed.");
RecordStore.deleteRecordStore("aRS3");
System.out.println("delete OK");
} catch (Exception x) {
}
} finally {
try {
if (rs != null)
rs.closeRecordStore();
rs.deleteRecordStore("aRS3");
} catch (Exception e) {
}
}
aTextBox.setString(result);
aTextBox.addCommand(exitCommand);
aTextBox.setCommandListener(this);
display.setCurrent(aTextBox);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
public boolean existing(String recordStoreName) {
boolean existingOrNot = false;
RecordStore rs = null;
if (recordStoreName.length() > 32)
return false;
try {
rs = RecordStore.openRecordStore(recordStoreName, false);
} catch (RecordStoreNotFoundException e) {
existingOrNot = false;
} catch (Exception e) {
} finally {
try {
rs.closeRecordStore();
} catch (Exception e) {
}
}
return existingOrNot;
}
public void commandAction(Command c, Displayable s) {
destroyApp(false);
notifyDestroyed();
}
}
class averageFilter implements RecordFilter {
public boolean matches(byte[] candidate) {
DataInputStream student = new DataInputStream(new ByteArrayInputStream(candidate));
int average = 0;
try {
String dummy = student.readUTF();
average = (student.readInt() + student.readInt() + student.readInt()) / 3;
} catch (Exception e) {
}
if (average >= 80)
return true;
else
return false;
}
}
class Student {
private int ID = -1;
private String name;
private int chineseScore;
private int englishScore;
private int mathScore;
public void write(String name, int chineseScore, int englishScore, int mathScore) {
this.name = name;
this.chineseScore = chineseScore;
this.englishScore = englishScore;
this.mathScore = mathScore;
}
public void setRecordID(int ID) {
this.ID = ID;
}
public int getRecordID() {
return ID;
}
public byte[] changeToByteArray() {
byte[] data = null;
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(baos);
dos.writeUTF(name);
dos.writeInt(chineseScore);
dos.writeInt(englishScore);
dos.writeInt(mathScore);
data = baos.toByteArray();
baos.close();
dos.close();
} catch (Exception e) {
}
return data;
}
public void changeFromByteArray(byte[] data) {
try {
ByteArrayInputStream bais = new ByteArrayInputStream(data);
DataInputStream dis = new DataInputStream(bais);
name = dis.readUTF();
chineseScore = dis.readInt();
englishScore = dis.readInt();
mathScore = dis.readInt();
bais.close();
dis.close();
} catch (Exception e) {
}
}
public String getName() {
return name;
}
public int getChineseScore() {
return chineseScore;
}
public int getEnglishScore() {
return englishScore;
}
public int getMathScore() {
return mathScore;
}
}
Get record from RecordStore
import javax.microedition.lcdui.rumand;
import javax.microedition.lcdui.rumandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.TextBox;
import javax.microedition.lcdui.TextField;
import javax.microedition.midlet.MIDlet;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreNotFoundException;
public class getRecordMIDlet extends MIDlet implements CommandListener {
private Command exitCommand = new Command("exit", Command.STOP, 1);
private Display display;
public getRecordMIDlet() {
display = Display.getDisplay(this);
}
public void startApp() {
TextBox aTextBox = new TextBox("Main", null, 256, TextField.ANY);
RecordStore rs = null;
boolean existingOrNot = false;
existingOrNot = existing("aRS");
if (existingOrNot) {
try {
rs = RecordStore.openRecordStore("aRS", false);
} catch (Exception e) {
}
} else {
try {
rs = RecordStore.openRecordStore("aRS", true);
} catch (Exception e) {
} finally {
}
}
try {
String record = "";
for (int i = 1; i < rs.getNextRecordID(); i++) {
record = new String(rs.getRecord(i));
}
aTextBox.setString(record);
} catch (Exception e) {
aTextBox.setString("Failed");
try {
rs.closeRecordStore();
RecordStore.deleteRecordStore("aRS");
} catch (Exception x) {
}
}
try {
rs.closeRecordStore();
} catch (Exception e) {
}
aTextBox.addCommand(exitCommand);
aTextBox.setCommandListener(this);
display.setCurrent(aTextBox);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
public boolean existing(String recordStoreName) {
boolean existingOrNot = false;
RecordStore rs = null;
if (recordStoreName.length() > 32)
return false;
try {
rs = RecordStore.openRecordStore(recordStoreName, false);
} catch (RecordStoreNotFoundException e) {
existingOrNot = false;
} catch (Exception e) {
} finally {
try {
rs.closeRecordStore();
} catch (Exception e) {
}
}
return existingOrNot;
}
public void commandAction(Command c, Displayable s) {
destroyApp(false);
notifyDestroyed();
}
}
Load yahoo stock quote
/* 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.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import javax.microedition.lcdui.Choice;
import javax.microedition.lcdui.rumand;
import javax.microedition.lcdui.rumandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.List;
import javax.microedition.lcdui.TextBox;
import javax.microedition.lcdui.TextField;
import javax.microedition.lcdui.Ticker;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
import javax.microedition.rms.RecordEnumeration;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreException;
import javax.microedition.rms.RecordStoreNotOpenException;
public class QuotesMIDlet extends MIDlet implements CommandListener {
Display display = null;
List menu = null; // main menu
List choose = null;
TextBox input = null;
Ticker ticker = new Ticker("Database Application");
String quoteServer = "http://quote.yahoo.ru/d/quotes.csv?s=";
String quoteFormat = "&f=slc1wop";
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;
// Stock data
String name, date, price;
StockDB db = null;
public QuotesMIDlet() {
}
public void startApp() throws MIDletStateChangeException {
display = Display.getDisplay(this);
// open a db stock file
try {
db = new StockDB("stocks");
} catch (Exception e) {
}
menu = new List("Stocks Database", Choice.IMPLICIT);
menu.append("List Stocks", null);
menu.append("Add A New Stock", null);
menu.addCommand(exitCommand);
menu.setCommandListener(this);
menu.setTicker(ticker);
mainMenu();
}
public void pauseApp() {
display = null;
choose = null;
menu = null;
ticker = null;
try {
db.close();
db = null;
} catch (Exception e) {
}
}
public void destroyApp(boolean unconditional) {
try {
db.close();
} catch (Exception e) {
}
notifyDestroyed();
}
void mainMenu() {
display.setCurrent(menu);
currentMenu = "Main";
}
public String tickerString() {
StringBuffer ticks = null;
try {
RecordEnumeration enum = db.enumerate();
ticks = new StringBuffer();
while (enum.hasNextElement()) {
String stock1 = new String(enum.nextRecord());
ticks.append(Stock.getName(stock1));
ticks.append(" @ ");
ticks.append(Stock.getPrice(stock1));
ticks.append(" ");
}
} catch (Exception ex) {
}
return (ticks.toString());
}
public void addStock() {
input = new TextBox("Enter a Stock Name:", "", 5, TextField.ANY);
input.setTicker(ticker);
input.addCommand(saveCommand);
input.addCommand(backCommand);
input.setCommandListener(this);
input.setString("");
display.setCurrent(input);
currentMenu = "Add";
}
public String getQuote(String input) throws IOException,
NumberFormatException {
String url = quoteServer + input + quoteFormat;
StreamConnection c = (StreamConnection) Connector.open(url,
Connector.READ_WRITE);
InputStream is = c.openInputStream();
StringBuffer sb = new StringBuffer();
int ch;
while ((ch = is.read()) != -1) {
sb.append((char) ch);
}
return (sb.toString());
}
public void listStocks() {
choose = new List("Choose Stocks", Choice.MULTIPLE);
choose.setTicker(new Ticker(tickerString()));
choose.addCommand(backCommand);
choose.setCommandListener(this);
try {
RecordEnumeration re = db.enumerate();
while (re.hasNextElement()) {
String theStock = new String(re.nextRecord());
choose.append(Stock.getName(theStock) + " @ "
+ Stock.getPrice(theStock), null);
}
} catch (Exception ex) {
}
display.setCurrent(choose);
currentMenu = "List";
}
public void commandAction(Command c, Displayable d) {
String label = c.getLabel();
if (label.equals("Exit")) {
destroyApp(true);
} else if (label.equals("Save")) {
if (currentMenu.equals("Add")) {
// add it to database
try {
String userInput = input.getString();
String pr = getQuote(userInput);
db.addNewStock(pr);
ticker.setString(tickerString());
} catch (IOException e) {
} catch (NumberFormatException se) {
}
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:
listStocks();
break;
case 1:
addStock();
break;
}
}
}
}
class StockDB {
RecordStore recordStore = null;
public StockDB() {
}
public StockDB(String fileName) {
try {
recordStore = RecordStore.openRecordStore(fileName, true);
} catch (RecordStoreException rse) {
rse.printStackTrace();
}
}
public void close() throws RecordStoreNotOpenException, RecordStoreException {
if (recordStore.getNumRecords() == 0) {
String fileName = recordStore.getName();
recordStore.closeRecordStore();
recordStore.deleteRecordStore(fileName);
} else {
recordStore.closeRecordStore();
}
}
public synchronized void addNewStock(String record) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream outputStream = new DataOutputStream(baos);
try {
outputStream.writeUTF(record);
} catch (IOException ioe) {
System.out.println(ioe);
ioe.printStackTrace();
}
byte[] b = baos.toByteArray();
try {
recordStore.addRecord(b, 0, b.length);
} catch (RecordStoreException rse) {
System.out.println(rse);
rse.printStackTrace();
}
}
public synchronized RecordEnumeration enumerate()
throws RecordStoreNotOpenException {
return recordStore.enumerateRecords(null, null, false);
}
}
/*
* 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.
*/
class Stock {
private static String name, time, price;
public static void parse(String data) {
int index = data.indexOf(""");
name = data.substring(++index, (index = data.indexOf(""", index)));
index += 3;
time = data.substring(index, (index = data.indexOf("-", index)) - 1);
index += 5;
price = data.substring(index, (index = data.indexOf("<", index)));
}
public static String getName(String record) {
parse(record);
return (name);
}
public static String getPrice(String record) {
parse(record);
return (price);
}
}
Mixed Record Enumeration
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
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.midlet.MIDlet;
import javax.microedition.rms.RecordEnumeration;
import javax.microedition.rms.RecordStore;
public class J2MEMixedRecordEnumerationExample extends MIDlet implements CommandListener {
private Display display;
private Alert alert;
private Form form = new Form("Mixed RecordEnumeration");
private Command exit = new Command("Exit", Command.SCREEN, 1);
private Command start = new Command("Start", Command.SCREEN, 1);
private RecordStore recordstore = null;
private RecordEnumeration recordEnumeration = null;
public J2MEMixedRecordEnumerationExample() {
display = Display.getDisplay(this);
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);
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();
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();
recordstore.closeRecordStore();
if (RecordStore.listRecordStores() != null) {
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);
}
}
}
}
Read and write mixed data types with RecordStore
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
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.midlet.MIDlet;
import javax.microedition.rms.RecordStore;
public class J2MEWriteReadMixedDataTypesExample extends MIDlet implements CommandListener {
private Display display;
private Alert alert;
private Form form = new Form("Mixed Record");
private Command exit = new Command("Exit", Command.SCREEN, 1);
private Command start = new Command("Start", Command.SCREEN, 1);
private RecordStore recordstore = null;
public J2MEWriteReadMixedDataTypesExample() {
display = Display.getDisplay(this);
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);
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();
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);
recordstore.closeRecordStore();
if (RecordStore.listRecordStores() != null) {
RecordStore.deleteRecordStore("myRecordStore");
}
} catch (Exception error) {
alert = new Alert("Error Removing", error.toString(), null, AlertType.WARNING);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert);
}
}
}
}
Record Enumeration
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.midlet.MIDlet;
import javax.microedition.rms.RecordEnumeration;
import javax.microedition.rms.RecordStore;
public class J2MERecordStoreExample extends MIDlet implements CommandListener {
private Display display;
private Alert alert;
private Form form = new Form("Record Store");
private Command exit = new Command("Exit", Command.SCREEN, 1);
private Command start = new Command("Start", Command.SCREEN, 1);
private RecordStore recordstore = null;
private RecordEnumeration recordenumeration = null;
public J2MERecordStoreExample() {
display = Display.getDisplay(this);
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 {
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);
}
}
}
}
}
Record Monitor
import javax.microedition.lcdui.rumand;
import javax.microedition.lcdui.rumandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.TextBox;
import javax.microedition.lcdui.TextField;
import javax.microedition.midlet.MIDlet;
import javax.microedition.rms.RecordListener;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreNotFoundException;
public class RecordMonitorMIDlet extends MIDlet implements CommandListener, RecordListener {
private Command exitCommand = new Command("Exit", Command.EXIT, 1);
private Command deleteCommand= new Command("Delete", Command.SCREEN, 1);
private Command changeCommand = new Command("Edit", Command.SCREEN, 1);
private Display display;
RecordStore mainRS = null;
RecordStore backupRS = null;
public RecordMonitorMIDlet() {
display = Display.getDisplay(this);
}
public void startApp() {
TextBox aTextBox = new TextBox("Main", null, 256, TextField.ANY);
byte[] nameEmail = null;
boolean existingOrNot = false;
boolean OK = true;
existingOrNot = existing("aRS1");
if (existingOrNot) {
try {
mainRS = RecordStore.openRecordStore("aRS1", false);
mainRS.addRecordListener(this);
} catch (Exception e) {
OK = false;
} finally {
if (OK) {
aTextBox.setString("Ok");
} else {
aTextBox.setString("Failed");
}
}
} else {
try {
mainRS = RecordStore.openRecordStore("aRS1", true);
mainRS.addRecordListener(this);
} catch (Exception e) {
OK = false;
} finally {
if (OK) {
aTextBox.setString("Ok");
} else {
aTextBox.setString("Falied");
}
}
}
if (OK)
try {
backupRS = RecordStore.openRecordStore("aRS2", true);
} catch (Exception e) {
}
if (OK)
try {
nameEmail = "JIDCA=login@yourname.net".getBytes();
mainRS.addRecord(nameEmail, 0, nameEmail.length);
aTextBox.setString("Added");
} catch (Exception e) {
aTextBox.setString("Add Falied");
}
String result = new String(nameEmail);
int position = result.indexOf("=");
result = "Name:" + result.substring(0, position) + "\n" + "E-mail?"
+ result.substring(position + 1, result.length());
aTextBox.setString(result);
try {
int recordID = mainRS.getNextRecordID() - 1;
byte[] newNameEmail = "Logis=login@yourname.net".getBytes();
mainRS.setRecord(recordID, newNameEmail, 0, newNameEmail.length);
recordID = mainRS.getNextRecordID() - 1;
mainRS.deleteRecord(recordID);
} catch (Exception e) {
}
aTextBox.addCommand(exitCommand);
aTextBox.addCommand(deleteCommand);
aTextBox.addCommand(changeCommand);
aTextBox.setCommandListener(this);
display.setCurrent(aTextBox);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
try {
if (mainRS != null) {
mainRS.closeRecordStore();
}
} catch (Exception e) {
}
try {
if (backupRS != null) {
backupRS.closeRecordStore();
}
} catch (Exception e) {
}
}
public boolean existing(String recordStoreName) {
boolean existingOrNot = false;
RecordStore mainRS = null;
if (recordStoreName.length() > 32)
return false;
try {
mainRS = RecordStore.openRecordStore(recordStoreName, false);
} catch (RecordStoreNotFoundException e) {
existingOrNot = false;
} catch (Exception e) {
} finally {
try {
mainRS.closeRecordStore();
} catch (Exception e) {
}
}
return existingOrNot;
}
public void commandAction(Command c, Displayable s) {
if (c == deleteCommand) {
try {
int recordID = mainRS.getNextRecordID() - 1;
mainRS.deleteRecord(recordID);
} catch (Exception e) {
}
} else if (c == changeCommand) {
try {
int recordID = mainRS.getNextRecordID() - 1;
byte[] newNameEmail = "Logis=login@yourname.net".getBytes();
mainRS.setRecord(recordID, newNameEmail, 0, newNameEmail.length);
} catch (Exception e) {
}
} else {
destroyApp(false);
notifyDestroyed();
}
}
public void recordAdded(RecordStore recordStore, int recordID) {
if (recordStore == mainRS) {
try {
byte[] data = recordStore.getRecord(recordID);
int recID = backupRS.addRecord(data, 0, data.length);
} catch (Exception e) {
}
}
}
public void recordChanged(RecordStore recordStore, int recordID) {
if (recordStore == mainRS) {
try {
byte[] data = recordStore.getRecord(recordID);
backupRS.setRecord(recordID, data, 0, data.length);
} catch (Exception e) {
}
}
}
public void recordDeleted(RecordStore recordStore, int recordID) {
if (recordStore == mainRS) {
try {
backupRS.deleteRecord(recordID);
} catch (Exception e) {
}
}
}
}
RecordStore read and write
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.midlet.MIDlet;
import javax.microedition.rms.RecordStore;
public class J2MEWriteReadExample extends MIDlet implements CommandListener {
private Display display;
private Alert alert;
private Form form = new Form("Record");
private Command exit = new Command("Exit", Command.SCREEN, 1);
private Command start = new Command("Start", Command.SCREEN, 1);
private RecordStore recordstore = null;
public J2MEWriteReadExample() {
display = Display.getDisplay(this);
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);
String outputData = "First Record";
byte[] byteOutputData = outputData.getBytes();
recordstore.addRecord(byteOutputData, 0, byteOutputData.length);
byte[] byteInputData = new byte[1];
int length = 0;
for (int x = 1; x <= recordstore.getNumRecords(); x++) {
if (recordstore.getRecordSize(x) > byteInputData.length) {
byteInputData = new byte[recordstore.getRecordSize(x)];
}
length = recordstore.getRecord(x, byteInputData, 0);
}
alert = new Alert("Reading", new String(byteInputData, 0, length), null, AlertType.WARNING);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert);
recordstore.closeRecordStore();
if (RecordStore.listRecordStores() != null) {
RecordStore.deleteRecordStore("myRecordStore");
}
} catch (Exception error) {
alert = new Alert("Error Removing", error.toString(), null, AlertType.WARNING);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert);
}
}
}
}
Retrieve All
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import javax.microedition.lcdui.rumand;
import javax.microedition.lcdui.rumandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.TextBox;
import javax.microedition.lcdui.TextField;
import javax.microedition.midlet.MIDlet;
import javax.microedition.rms.RecordEnumeration;
import javax.microedition.rms.RecordFilter;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreNotFoundException;
public class RetrieveAllMIDlet extends MIDlet implements CommandListener {
private Command exitCommand = new Command("Exit", Command.EXIT, 1);
private Display display;
private String[] names = { "A", "B", "C", "D" };
private int[] chineseScore = { 74, 98, 89, 76 };
private int[] englishScore = { 67, 89, 89, 78 };
private int[] mathScore = { 80, 76, 80, 78 };
public RetrieveAllMIDlet() {
display = Display.getDisplay(this);
}
public void startApp() {
TextBox aTextBox = new TextBox("Main", null, 256, TextField.ANY);
RecordStore rs = null;
boolean existingOrNot = false;
existingOrNot = existing("aRS3");
if (existingOrNot) {
try {
rs = RecordStore.openRecordStore("aRS3", false);
} catch (Exception e) {
}
} else {
try {
rs = RecordStore.openRecordStore("aRS3", true);
} catch (Exception e) {
}
}
Student aStudent = null;
try {
for (int i = 0; i < names.length; i++) {
aStudent = new Student();
aStudent.write(names[i], chineseScore[i], englishScore[i], mathScore[i]);
byte[] data = aStudent.changeToByteArray();
int recordID = aStudent.getRecordID();
if (recordID != -1) {
rs.setRecord(recordID, data, 0, data.length);
} else {
recordID = rs.addRecord(data, 0, data.length);
aStudent.setRecordID(recordID);
}
aStudent = null;
}
aTextBox.setString("Adding done");
} catch (Exception e) {
aTextBox.setString("Add Falied");
}
String result = "";
aStudent = new Student();
try {
byte[] data;
int number = 0;
RecordFilter rf = new averageFilter();
RecordEnumeration re = rs.enumerateRecords(rf, null, false);
while (re.hasNextElement()) {
int recordID = re.nextRecordId();
data = rs.getRecord(recordID);
aStudent.changeFromByteArray(data);
result += recordID + "\n" + "Name:" + aStudent.getName() + "\n" + ":"
+ aStudent.getChineseScore() + "\n" + ":" + aStudent.getEnglishScore() + "\n" + ":"
+ aStudent.getMathScore() + "\n";
number++;
}
result += number + "\n";
aTextBox.setString(result);
} catch (Exception e) {
aTextBox.setString("Failed!");
try {
rs.closeRecordStore();
RecordStore.deleteRecordStore("aRS3");
} catch (Exception x) {
}
} finally {
try {
if (rs != null)
rs.closeRecordStore();
rs.deleteRecordStore("aRS3");
} catch (Exception e) {
}
}
aTextBox.setString(result);
aTextBox.addCommand(exitCommand);
aTextBox.setCommandListener(this);
display.setCurrent(aTextBox);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
public boolean existing(String recordStoreName) {
boolean existingOrNot = false;
RecordStore rs = null;
if (recordStoreName.length() > 32)
return false;
try {
rs = RecordStore.openRecordStore(recordStoreName, false);
} catch (RecordStoreNotFoundException e) {
existingOrNot = false;
} catch (Exception e) {
} finally {
try {
rs.closeRecordStore();
} catch (Exception e) {
}
}
return existingOrNot;
}
public void commandAction(Command c, Displayable s) {
destroyApp(false);
notifyDestroyed();
}
}
class Student {
private int ID = -1;
private String name;
private int chineseScore;
private int englishScore;
private int mathScore;
public void write(String name, int chineseScore, int englishScore, int mathScore) {
this.name = name;
this.chineseScore = chineseScore;
this.englishScore = englishScore;
this.mathScore = mathScore;
}
public void setRecordID(int ID) {
this.ID = ID;
}
public int getRecordID() {
return ID;
}
public byte[] changeToByteArray() {
byte[] data = null;
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(baos);
dos.writeUTF(name);
dos.writeInt(chineseScore);
dos.writeInt(englishScore);
dos.writeInt(mathScore);
data = baos.toByteArray();
baos.close();
dos.close();
} catch (Exception e) {
}
return data;
}
public void changeFromByteArray(byte[] data) {
try {
ByteArrayInputStream bais = new ByteArrayInputStream(data);
DataInputStream dis = new DataInputStream(bais);
name = dis.readUTF();
chineseScore = dis.readInt();
englishScore = dis.readInt();
mathScore = dis.readInt();
bais.close();
dis.close();
} catch (Exception e) {
}
}
public String getName() {
return name;
}
public int getChineseScore() {
return chineseScore;
}
public int getEnglishScore() {
return englishScore;
}
public int getMathScore() {
return mathScore;
}
}
class averageFilter implements RecordFilter {
public boolean matches(byte[] candidate) {
DataInputStream student = new DataInputStream(new ByteArrayInputStream(candidate));
int average = 0;
try {
average = (student.readInt() + student.readInt() + student.readInt()) / 3;
} catch (Exception e) {
}
if (average >= 80)
return true;
else
return false;
}
}
Save data to RecordStore
import javax.microedition.lcdui.rumand;
import javax.microedition.lcdui.rumandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.TextBox;
import javax.microedition.lcdui.TextField;
import javax.microedition.midlet.MIDlet;
import javax.microedition.rms.InvalidRecordIDException;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreException;
import javax.microedition.rms.RecordStoreNotFoundException;
import javax.microedition.rms.RecordStoreNotOpenException;
public class RecordIDMIDlet extends MIDlet implements CommandListener {
private Command exitCommand= new Command("Exit", Command.EXIT, 1);
private Display display;
public RecordIDMIDlet() {
display = Display.getDisplay(this);
}
public void startApp() {
TextBox aTextBox = new TextBox("Main", null, 256, TextField.ANY);
RecordStore rs = null;
byte[] name = null;
boolean existingOrNot = false;
boolean OK = true;
existingOrNot = existing("aRS");
if (existingOrNot) {
try {
rs = RecordStore.openRecordStore("aRS", false);
} catch (Exception e) {
OK = false;
} finally {
if (OK) {
aTextBox.setString("Ok");
} else {
aTextBox.setString("Failed");
}
}
} else {
try {
rs = RecordStore.openRecordStore("aRS", true);
} catch (Exception e) {
OK = false;
} finally {
if (OK) {
aTextBox.setString("Ok");
} else {
aTextBox.setString("Failed");
}
}
}
if (OK) {
try {
for (int i = 1; i <= 3; i++) {
name = ("Name " + i).getBytes();
rs.addRecord(name, 0, name.length);
}
} catch (Exception e) {
aTextBox.setString("Add Falied");
}
try {
rs.deleteRecord(1);
aTextBox.setString("recordID Delete");
} catch (InvalidRecordIDException e) {
try {
aTextBox.setString(rs.getNumRecords() + "recordID");
} catch (RecordStoreNotOpenException rse) {
}
} catch (RecordStoreException e) {
} finally {
try {
rs.closeRecordStore();
} catch (Exception e) {
}
}
}
aTextBox.addCommand(exitCommand);
aTextBox.setCommandListener(this);
display.setCurrent(aTextBox);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
public boolean existing(String recordStoreName) {
boolean existingOrNot = false;
RecordStore rs = null;
if (recordStoreName.length() > 32)
return false;
try {
rs = RecordStore.openRecordStore(recordStoreName, false);
} catch (RecordStoreNotFoundException e) {
existingOrNot = false;
} catch (Exception e) {
} finally {
try {
rs.closeRecordStore();
} catch (Exception e) {
}
}
return existingOrNot;
}
public void commandAction(Command c, Displayable s) {
destroyApp(false);
notifyDestroyed();
}
}
Search Mixed Record Data Type
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
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.midlet.MIDlet;
import javax.microedition.rms.RecordEnumeration;
import javax.microedition.rms.RecordFilter;
import javax.microedition.rms.RecordStore;
public class J2MESearchMixedRecordDataTypeExample extends MIDlet implements CommandListener {
private Display display;
private Alert alert;
private Form form = new Form("Mixed RecordEnumeration");
private Command exit = new Command("Exit", Command.SCREEN, 1);
private Command start = new Command("Start", Command.SCREEN, 1);
private RecordStore recordstore = null;
private RecordEnumeration recordEnumeration = null;
private Filter filter = null;
public J2MESearchMixedRecordDataTypeExample() {
display = Display.getDisplay(this);
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);
byte[] outputRecord;
String outputString[] = { "A", "B", "M" };
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();
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();
recordstore.closeRecordStore();
if (RecordStore.listRecordStores() != null) {
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) {
}
}
}
Search record in RecordStore
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
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.midlet.MIDlet;
import javax.microedition.rms.RecordEnumeration;
import javax.microedition.rms.RecordFilter;
import javax.microedition.rms.RecordStore;
public class J2MESearchExample extends MIDlet implements CommandListener {
private Display display;
private Alert alert;
private Form form = new Form("Mixed RecordEnumeration", null);
private Command exit = new Command("Exit", Command.SCREEN, 1);
private Command start = new Command("Start", Command.SCREEN, 1);
private RecordStore recordstore = null;
private RecordEnumeration recordEnumeration = null;
private Filter filter = null;
public J2MESearchExample() {
display = Display.getDisplay(this);
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);
String outputData[] = { "M", "B", "A" };
for (int x = 0; x < 3; x++) {
byte[] byteOutputData = outputData[x].getBytes();
recordstore.addRecord(byteOutputData, 0, byteOutputData.length);
}
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);
}
recordstore.closeRecordStore();
if (RecordStore.listRecordStores() != null) {
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) {
}
}
}
Sort Fields
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import javax.microedition.lcdui.rumand;
import javax.microedition.lcdui.rumandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.TextBox;
import javax.microedition.lcdui.TextField;
import javax.microedition.midlet.MIDlet;
import javax.microedition.rms.RecordComparator;
import javax.microedition.rms.RecordEnumeration;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreNotFoundException;
public class SortFieldsMIDlet extends MIDlet implements CommandListener {
private Command exitCommand = new Command("Exit", Command.EXIT, 1);
private Display display;
private String[] names = { "A", "B", "C", "D" };
private int[] chineseScore = { 74, 98, 89, 76 };
private int[] englishScore = { 67, 89, 89, 78 };
private int[] mathScore = { 80, 76, 80, 78 };
public SortFieldsMIDlet() {
display = Display.getDisplay(this);
}
public void startApp() {
TextBox aTextBox = new TextBox("Main", null, 256, TextField.ANY);
RecordStore rs = null;
boolean existingOrNot = false;
existingOrNot = existing("aRS3");
if (existingOrNot) {
try {
rs = RecordStore.openRecordStore("aRS3", false);
} catch (Exception e) {
}
} else {
try {
rs = RecordStore.openRecordStore("aRS3", true);
} catch (Exception e) {
}
}
Student aStudent = null;
try {
for (int i = 0; i < names.length; i++) {
aStudent = new Student();
aStudent.write(names[i], chineseScore[i], englishScore[i], mathScore[i]);
byte[] data = aStudent.changeToByteArray();
int recordID = aStudent.getRecordID();
if (recordID != -1) {
rs.setRecord(recordID, data, 0, data.length);
} else {
recordID = rs.addRecord(data, 0, data.length);
aStudent.setRecordID(recordID);
}
aStudent = null;
}
String result = "";
aStudent = new Student();
byte[] data;
int number = 0;
RecordComparator rc = new sortByAverage();
RecordEnumeration re = rs.enumerateRecords(null, rc, false);
while (re.hasNextElement()) {
int recordID = re.nextRecordId();
data = rs.getRecord(recordID);
aStudent.changeFromByteArray(data);
result += recordID + "\n" + "Name:" + aStudent.getName() + "\n" + ":"
+ aStudent.getChineseScore() + "\n" + ":" + aStudent.getEnglishScore() + "\n" + ":"
+ aStudent.getMathScore() + "\n";
number++;
}
result += "" + number + "\n";
aTextBox.setString(result);
aTextBox.setString(result);
aTextBox.addCommand(exitCommand);
aTextBox.setCommandListener(this);
display.setCurrent(aTextBox);
} catch (Exception e) {
}
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
public boolean existing(String recordStoreName) {
boolean existingOrNot = false;
RecordStore rs = null;
if (recordStoreName.length() > 32)
return false;
try {
rs = RecordStore.openRecordStore(recordStoreName, false);
} catch (RecordStoreNotFoundException e) {
existingOrNot = false;
} catch (Exception e) {
} finally {
try {
rs.closeRecordStore();
} catch (Exception e) {
}
}
return existingOrNot;
}
public void commandAction(Command c, Displayable s) {
destroyApp(false);
notifyDestroyed();
}
}
class Student {
private int ID = -1;
private String name;
private int chineseScore;
private int englishScore;
private int mathScore;
public void write(String name, int chineseScore, int englishScore, int mathScore) {
this.name = name;
this.chineseScore = chineseScore;
this.englishScore = englishScore;
this.mathScore = mathScore;
}
public void setRecordID(int ID) {
this.ID = ID;
}
public int getRecordID() {
return ID;
}
public byte[] changeToByteArray() {
byte[] data = null;
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(baos);
dos.writeUTF(name);
dos.writeInt(chineseScore);
dos.writeInt(englishScore);
dos.writeInt(mathScore);
data = baos.toByteArray();
baos.close();
dos.close();
} catch (Exception e) {
}
return data;
}
public void changeFromByteArray(byte[] data) {
try {
ByteArrayInputStream bais = new ByteArrayInputStream(data);
DataInputStream dis = new DataInputStream(bais);
name = dis.readUTF();
chineseScore = dis.readInt();
englishScore = dis.readInt();
mathScore = dis.readInt();
bais.close();
dis.close();
} catch (Exception e) {
}
}
public String getName() {
return name;
}
public int getChineseScore() {
return chineseScore;
}
public int getEnglishScore() {
return englishScore;
}
public int getMathScore() {
return mathScore;
}
}
class sortByAverage implements RecordComparator {
public int compare(byte[] rec1, byte[] rec2) {
DataInputStream student1 = new DataInputStream(new ByteArrayInputStream(rec1));
DataInputStream student2 = new DataInputStream(new ByteArrayInputStream(rec2));
int average1 = 0;
int average2 = 0;
try {
average1 = (student1.readInt() + student1.readInt() + student1.readInt()) / 3;
average2 = (student2.readInt() + student2.readInt() + student2.readInt()) / 3;
} catch (Exception e) {
}
if (average1 == average2)
return RecordComparator.EQUIVALENT;
else if (average1 < average2)
return RecordComparator.FOLLOWS;
else
return RecordComparator.PRECEDES;
}
}
Sort Mixed Record DataType
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
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.midlet.MIDlet;
import javax.microedition.rms.RecordComparator;
import javax.microedition.rms.RecordEnumeration;
import javax.microedition.rms.RecordStore;
public class J2MESortMixedRecordDataTypeExample extends MIDlet implements CommandListener {
private Display display;
private Alert alert;
private Form form = new Form("Mixed RecordEnumeration");
private Command exit = new Command("Exit", Command.SCREEN, 1);
private Command start = new Command("Start", Command.SCREEN, 1);
private RecordStore recordstore = null;
private RecordEnumeration recordEnumeration = null;
private Comparator comparator = null;
public J2MESortMixedRecordDataTypeExample() {
display = Display.getDisplay(this);
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);
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();
String[] inputString = new String[3];
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();
recordstore.closeRecordStore();
if (RecordStore.listRecordStores() != null) {
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 records in RecordStore
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.midlet.MIDlet;
import javax.microedition.rms.RecordComparator;
import javax.microedition.rms.RecordEnumeration;
import javax.microedition.rms.RecordStore;
public class J2MESortExample extends MIDlet implements CommandListener {
private Display display;
private Alert alert;
private Form form = new Form("Mixed RecordEnumeration", null);
private Command exit = new Command("Exit", Command.SCREEN, 1);
private Command start = new Command("Start", Command.SCREEN, 1);
private RecordStore recordstore = null;
private RecordEnumeration recordEnumeration = null;
private Comparator comparator = null;
public J2MESortExample() {
display = Display.getDisplay(this);
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);
String outputData[] = { "M", "B", "A" };
for (int x = 0; x < 3; x++) {
byte[] byteOutputData = outputData[x].getBytes();
recordstore.addRecord(byteOutputData, 0, byteOutputData.length);
}
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);
recordstore.closeRecordStore();
if (RecordStore.listRecordStores() != null) {
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;
}
}