×
Namespaces

Variants
Actions
(Difference between revisions)

Storing application settings in Java ME

From Nokia Developer Wiki
Jump to: navigation, search
dekudin (Talk | contribs)
vvsnaresh (Talk | contribs)
(Category added)
Line 496: Line 496:
  
 
Executables and source files can be found in [[Media:Storing_application_settings.zip]]
 
Executables and source files can be found in [[Media:Storing_application_settings.zip]]
 +
[[Category:Java ME]]

Revision as of 20:05, 21 November 2008


Article Metadata
Tested with
Devices(s): Nokia E70
CompatibilityArticle
Keywords: avax.microedition.rms.RecordStore, javax.microedition.rms.RecordEnumeration, javax.microedition.rms.RecordStore.addRecord, javax.microedition.rms.RecordStore.enumerateRecords
Created: (31 Oct 2008)
Last edited: vvsnaresh (21 Nov 2008)


Overview

This code snippet demonstrates how to store application settings using RMS (Record Management System).

To store application settings in RMS database following steps must be performed:

  1. Open or create RMS database for application using method RecordStore.openRecordStore. This method returns RecordStore objects represents application database.
  2. Serialize app-defined data structure for setting to array of byte.
  3. Execute RecordStore.addRecord method on database object and pass array of bytes as parameter.
  4. Close RMS database.

This midlet consists of 3 source files:

  1. StoringAppSettings.java - contains midlet class.
  2. AppSetting.java - contains application setting class. This class stores application setting values and has methods for serializing and deserializing.
  3. AddSettingForm.java - contains form that lets user to enter name and value of new application setting.

Source file: StoringAppSettings.java

import javax.microedition.midlet.MIDlet;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.List;
 
import javax.microedition.rms.RecordEnumeration;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreException;
import javax.microedition.rms.RecordStoreNotOpenException;
import javax.microedition.rms.RecordListener;
 
import java.util.Vector;
 
 
public class StoringAppSettings extends MIDlet
implements CommandListener, RecordListener {
 
private Display display;
// List for displaying settings of application.
private List recordList;
// Command for adding new setting.
private Command cmdAdd;
// Command for deleteing all records from record store.
private Command cmdDeleteAll;
// Command for exiting from midlet.
private Command cmdExit;
 
// Name of record store of application.
private final String RECORD_STORE_NAME = "StoringAppSettingsStore";
// Record store of application.
private RecordStore recordStore;
// Array of settings deserialized from records in record store.
private Vector appSettings;
 
// Form for adding new setting.
private AddSettingForm addSettingForm;
 
/**
* Constructor
*/

public StoringAppSettings() {
initializeComponents();
}
 
/**
* Initializes components of midlet
*/

private void initializeComponents() {
// Get display
display = Display.getDisplay(this);
 
// Create recordList
recordList = new List("App settings", List.IMPLICIT);
cmdAdd = new Command("Add setting", Command.SCREEN, 0);
recordList.addCommand(cmdAdd);
cmdDeleteAll = new Command("Delete all settings", Command.SCREEN, 0);
recordList.addCommand(cmdDeleteAll);
cmdExit = new Command("Exit", Command.EXIT, 0);
recordList.addCommand(cmdExit);
recordList.setCommandListener(this);
 
// Create form for adding new settings.
addSettingForm = new AddSettingForm();
addSettingForm.setCommandListener(this);
 
// Create array of app settings.
appSettings = new Vector();
 
// Open record store, read settings from it and display settings.
openRecordStore();
getAppSettings();
addSettingsToForm();
}
 
/**
* Opens named record store of application. Record store will be created
* if it is not exists.
*/

private void openRecordStore() {
try {
recordStore = RecordStore.openRecordStore(RECORD_STORE_NAME, true);
recordStore.addRecordListener(this);
 
} catch(RecordStoreException rsExc) {
// TODO: Handle error.
} catch(Exception exc) {
// TODO: Handle error.
}
}
 
/**
* Closes record store.
*/

private void closeRecordStore() {
try {
recordStore.closeRecordStore();
} catch (RecordStoreNotOpenException ex) {
// TODO: Handle error.
} catch (RecordStoreException ex) {
// TODO: Handle error.
}
}
 
/**
* Reads settings from record store and adds it to array of settings.
*/

private void getAppSettings() {
try {
appSettings.removeAllElements();
 
RecordEnumeration recEnum = recordStore.enumerateRecords(null,
null, false);
while(recEnum.hasNextElement() == true) {
int settingId = recEnum.nextRecordId();
byte[] data = recordStore.getRecord(settingId);
AppSetting setting = AppSetting.deserialize(data);
if(setting != null) {
appSettings.addElement(setting);
}
}
recEnum.destroy();
 
} catch(Exception exc) {
// TODO: Handle error.
}
}
 
/**
* Adds settings to settings list control from array of settings.
*/

private void addSettingsToForm() {
recordList.deleteAll();
 
for(int index = 0; index < appSettings.size(); ++index) {
AppSetting setting = (AppSetting)appSettings.elementAt(index);
recordList.append(setting.toString(), null);
}
}
 
/**
* Adds setting to record store.
* @param name - name of new record.
* @param value - value of new record.
*/

private void addSetting(String name, String value) {
try {
AppSetting setting = new AppSetting(name, value);
byte[] data = setting.serialize();
recordStore.addRecord(data, 0, data.length);
} catch(Exception exc) {
// TODO: Handle error.
}
}
 
/**
* Deletes record store and creates it again.
*/

private void deleteAllSettings() {
try {
recordStore.closeRecordStore();
RecordStore.deleteRecordStore(RECORD_STORE_NAME);
} catch(Exception exc) {
// TODO: handle something.
}
 
openRecordStore();
}
 
/**
* From MIDlet.
* Signals the MIDlet that it has entered the Active state.
*/

public void startApp() {
display.setCurrent(recordList);
}
 
/**
* From MIDlet.
* Signals the MIDlet to enter the Paused state.
*/

public void pauseApp() {
// No implementation required
}
 
/**
* From MIDlet.
* Signals the MIDlet to terminate and enter the Destroyed state.
*/

public void destroyApp(boolean unconditional) {
closeRecordStore();
}
 
/**
* Performs exit from midlet.
*/

private void exitMIDlet() {
notifyDestroyed();
}
 
/**
* From CommandListener.
* Indicates that a command event has occurred on Displayable d.
* @param cmd - a Command object identifying the command.
* @param d - the Displayable on which this event has occurred.
*/

public void commandAction(Command cmd, Displayable d) {
if(d == recordList) {
if(cmd == cmdAdd) {
addSettingForm.clear();
display.setCurrent(addSettingForm);
}
if(cmd == cmdDeleteAll) {
deleteAllSettings();
getAppSettings();
addSettingsToForm();
}
if(cmd == cmdExit) {
exitMIDlet();
}
}
if(d == addSettingForm) {
if(cmd == addSettingForm.getSaveCommand()) {
addSetting(addSettingForm.getName(), addSettingForm.getValue());
display.setCurrent(recordList);
}
if(cmd == addSettingForm.getBackCommand()) {
display.setCurrent(recordList);
}
}
}
 
/**
* From RecordListener.
* Called when a record has been added to a record store.
* @param store - the RecordStore in which the record is stored
* @param recordId - the recordId of the record that has been added
*/

public void recordAdded(RecordStore store, int recordId) {
getAppSettings();
addSettingsToForm();
}
 
/**
* From RecordListener.
* Called after a record in a record store has been changed.
* @param store - the RecordStore in which the record is stored
* @param recordId - the recordId of the record that has been added
*/

public void recordChanged(RecordStore store, int recordId) {
// No implementation required.
}
 
/**
* From RecordListener.
* Called after a record has been deleted from a record store.
* @param store - the RecordStore in which the record is stored
* @param recordId - the recordId of the record that has been added
*/

public void recordDeleted(RecordStore store, int recordId) {
// No implementation required.
}
}

Source file: AppSetting.java

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
 
/**
* Setting of application. Consist of pair "name - value"
*/

public class AppSetting {
// Name of setting.
private String name;
// Value of setting.
private String value;
 
/**
* Constructor.
* @param name - name of new setting.
* @param value - value of new setting.
*/

public AppSetting(String name, String value) {
this.name = name;
this.value = value;
}
 
/**
* Deserializes app setting from data buffer and returns it.
* @param data - data for creating new setting.
* @return new setting.
*/

public static AppSetting deserialize(byte[] data) {
String name = null;
String value = null;
 
try {
ByteArrayInputStream byteInStream = new ByteArrayInputStream(data);
DataInputStream dataInStream = new DataInputStream(byteInStream);
 
name = dataInStream.readUTF();
value = dataInStream.readUTF();
 
dataInStream.close();
byteInStream.close();
 
} catch(Exception exc) {
return null;
}
 
return new AppSetting(name, value);
}
 
/**
* Serilizes setting to array of bytes.
* @return array of bytes representing serialized setting.
*/

public byte[] serialize() {
byte[] data = null;
 
try {
ByteArrayOutputStream byteOutStream = new ByteArrayOutputStream();
DataOutputStream dataOutStream = new DataOutputStream(byteOutStream);
 
dataOutStream.writeUTF(name);
dataOutStream.writeUTF(value);
 
dataOutStream.flush();
data = byteOutStream.toByteArray();
 
dataOutStream.close();
byteOutStream.close();
 
} catch(Exception exc) {
return null;
}
 
return data;
}
 
/**
* Gets name of setting.
* @return name of setting.
*/

public String getName() {
return name;
}
 
/**
* Gets value of setting.
* @return value of setting.
*/

public String getValue() {
return value;
}
 
/**
* Returns textual representation of setting.
* @return textual representation of setting.
*/

public String toString() {
return name + ": " + value;
}
}

Source file: AddSettingForm.java

import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.TextField;
import javax.microedition.lcdui.Command;
 
/**
* Form for receiving from user name and value of new setting.
*/

public class AddSettingForm extends Form {
// Text field for entering name of new setting.
private TextField nameField;
// Text field for entering value of new setting.
private TextField valueField;
 
// Command for saving new setting in record store.
private Command cmdSave;
// Command for altering saving new setting.
private Command cmdBack;
 
/**
* Constructor.
*/

public AddSettingForm() {
super("Add setting");
 
nameField = new TextField("Name", null, 30, 0);
append(nameField);
valueField = new TextField("Value", null, 30, 0);
append(valueField);
 
cmdSave = new Command("Save", Command.SCREEN, 0);
addCommand(cmdSave);
cmdBack = new Command("Back", Command.BACK, 0);
addCommand(cmdBack);
}
 
/**
* Clears antered values in text fields of form.
*/

public void clear() {
nameField.setString(null);
valueField.setString(null);
}
 
/**
* Gets from name text field name of new setting and returns it.
* @return name of new setting.
*/

public String getName() {
return nameField.getString();
}
 
/**
* Gets from value text field value of new setting and returns it.
* @return value of new setting.
*/

public String getValue() {
return valueField.getString();
}
 
/**
* @return command for saving new setting in record store.
*/

public Command getSaveCommand() {
return cmdSave;
}
 
/**
* @return command for altering saving new setting.
*/

public Command getBackCommand() {
return cmdBack;
}
}


Postconditions

List of application settings is shown on display.

By pressing "Add setting" menu command user can create new application setting. By pressing "Delete all settings" menu command user can delete all application settings.

Supplementary material

Executables and source files can be found in Media:Storing_application_settings.zip

144 page views in the last 30 days.