Skip to content

Instantly share code, notes, and snippets.

@nathanpc
Created June 18, 2011 15:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nathanpc/1033215 to your computer and use it in GitHub Desktop.
Save nathanpc/1033215 to your computer and use it in GitHub Desktop.
Fully Featured RecordStore Example(Java ME)
package contacts;
import java.io.*;
import java.util.Vector;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
import javax.microedition.rms.*;
import javax.microedition.lcdui.*;
public class simplecontacts extends MIDlet implements CommandListener {
private Display display;
private Alert alerta;
private Form initialScreen, addReg;
private TextField name, telefone;
private Command exit, add, back, save, clear;
private RecordStore rs = null;
String type, message;
boolean recordOK = false;
private ChoiceGroup contact_type;
private String[] listType = {"Amigos", "Família", "Trabalho", "Teste"};
private Form listReg;
private Command list, delete, ord, filter;
private ChoiceGroup listRegistrys;
boolean deletedFlags[] = null;
private Vector vecNames;
public simplecontacts() {
display = Display.getDisplay(this);
exit = new Command("Exit", Command.EXIT, 0);
add = new Command("Add Registrys", Command.SCREEN, 1);
clear = new Command("Clear Registrys", Command.SCREEN, 1);
back = new Command("Back", Command.SCREEN, 1);
save = new Command("Save Registry", Command.SCREEN, 1);
name = new TextField("Name:", "", 20, TextField.ANY);
telefone = new TextField("Telefone:", "", 10, TextField.PHONENUMBER);
list = new Command("List Registrys", Command.SCREEN, 1);
listRegistrys = new ChoiceGroup("Registrys", ChoiceGroup.MULTIPLE);
vecNames = new Vector();
delete = new Command("Delete Registrys", Command.SCREEN, 1);
ord = new Command("Order Registrys", Command.SCREEN, 1);
filter = new Command("Filter Registrys", Command.SCREEN, 1);
initialScreen = new Form("Simple Contacts");
initialScreen.addCommand(exit);
initialScreen.addCommand(add);
initialScreen.addCommand(clear);
initialScreen.addCommand(list);
initialScreen.addCommand(ord);
initialScreen.addCommand(filter);
initialScreen.addCommand(clear);
initialScreen.setCommandListener(this);
addReg = new Form("Add Contact");
contact_type = new ChoiceGroup("Types", Choice.POPUP, listType, null);
addReg.append(name);
addReg.append(telefone);
addReg.append(contact_type);
addReg.addCommand(save);
addReg.addCommand(back);
addReg.setCommandListener(this);
listReg = new Form("");
listReg.append(listRegistrys);
listReg.addCommand(delete);
listReg.addCommand(back);
listReg.setCommandListener(this);
}
protected void destroyApp(boolean arg0) {
notifyDestroyed();
}
protected void pauseApp() {
}
protected void startApp() throws MIDletStateChangeException {
try {
rs = RecordStore.openRecordStore("SContacts", true);
} catch (Exception exc) {
mostrarAlerta("Erro ao abrir o RecordStore -", exc.toString());
}
display.setCurrent(initialScreen);
}
private void gerarTela(Vector nomes, int totalElementos) {
for (int i = listRegistrys.size(); i > 0; i--)
listRegistrys.delete(i - 1);
for (int i = 0; i < nomes.size(); i++) {
Nomes item = (Nomes) vecNames.elementAt(i);
String nome = item.getNome();
String telefone = item.getTelefone();
listRegistrys.append(nome + " " + telefone, null);
}
display.setCurrent(listReg);
}
private void listarRegistros(FiltroNome f, ComparadorNome c) {
RecordEnumeration rEnum = null;
vecNames.removeAllElements();
try {
rEnum = rs.enumerateRecords(f, c, false);
int posicao = 0;
while (rEnum.hasNextElement()) {
int id = rEnum.nextRecordId();
byte[] dados = rs.getRecord(id);
ByteArrayInputStream BAIS = new ByteArrayInputStream(dados);
DataInputStream DIS = new DataInputStream(BAIS);
String nomeLido = DIS.readUTF();
String telefoneLido = DIS.readUTF();
int tipo = DIS.readInt();
Nomes itemAgenda = new Nomes(nomeLido, telefoneLido, tipo, id, posicao);
vecNames.addElement(itemAgenda);
posicao++;
}
gerarTela(vecNames, rEnum.numRecords());
} catch (Exception exc) {
mostrarAlerta("Erro na listagem -", exc.toString());
} finally {
rEnum.destroy();
}
}
private void apagarRegistros() {
try {
for (int i = 0; i < deletedFlags.length; i++) {
if (deletedFlags[i] == true) {
Nomes itemAgenda = (Nomes) vecNames.elementAt(i);
try {
rs.deleteRecord(itemAgenda.getRecordId());
} catch (Exception exc) {
}
}
}
display.setCurrent(initialScreen);
} catch (Exception exc) {
Alert erro = new Alert("Nenhum registro foi selecionado -",
"Refaça a operação ou volte para a tela inicial", null, AlertType.ERROR);
erro.setTimeout(Alert.FOREVER);
display.setCurrent(erro);
}
}
private void mostrarAlerta(String tipoAlerta, String msg) {
alerta = new Alert(tipoAlerta, msg, null, AlertType.WARNING);
alerta.setTimeout(Alert.FOREVER);
display.setCurrent(alerta);
}
private void adicionarRegistro() {
try {
ByteArrayOutputStream BAOS = new ByteArrayOutputStream();
DataOutputStream DOS = new DataOutputStream(BAOS);
DOS.writeUTF(name.getString());
DOS.writeUTF(telefone.getString());
DOS.writeInt(contact_type.getSelectedIndex());
byte [] bRec = BAOS.toByteArray();
rs.addRecord(bRec, 0, bRec.length);
DOS.close();
BAOS.close();
display.setCurrent(initialScreen);
} catch (Exception exc) {
mostrarAlerta("Erro ao adicionar -", exc.toString());
}
}
private void zerarRegistros(){
try {
rs.closeRecordStore();
RecordStore.deleteRecordStore("SContacts");
rs = RecordStore.openRecordStore("SContacts", true);
} catch (Exception exc) {
mostrarAlerta("Erro ao recriar o RecordStore -", exc.toString());
}
display.setCurrent(initialScreen);
}
public void commandAction(Command com, Displayable dis) {
if (com == exit) {
try {
rs.closeRecordStore();
} catch (Exception exc) {
mostrarAlerta("Erro fechando o RecordStore -", exc.toString());
}
destroyApp(true);
} else if (com == add) {
name.setString("");
telefone.setString("");
display.setCurrent(addReg);
} else if (com == save) {
adicionarRegistro();
} else if (com == clear) {
zerarRegistros();
} else if (com == back) {
display.setCurrent(initialScreen);
} else if (com == delete) {
apagarRegistros();
} else if (com == list) {
listReg.setTitle("Listing All");
listRegistrys.deleteAll();
listarRegistros(null, null);
} else if (com == ord) {
listReg.setTitle("Registrys Ordened");
listRegistrys.deleteAll();
ComparadorNome comparador = new ComparadorNome();
listarRegistros(null, comparador);
} else if (com == filter) {
listReg.setTitle("Filtred Registrys");
listRegistrys.deleteAll();
FiltroNome filtro = new FiltroNome("Thiago");
ComparadorNome comparador = new ComparadorNome();
listarRegistros(filtro, comparador);
}
}
}
class FiltroNome implements RecordFilter {
String nome;
public FiltroNome(String nomeFiltrado) {
nome = nomeFiltrado;
}
public boolean matches(byte[] registro) {
try {
ByteArrayInputStream BAIS = new ByteArrayInputStream(registro);
DataInputStream DIS = new DataInputStream(BAIS);
String nomeLido = DIS.readUTF();
DIS.close();
BAIS.close();
if (nome.compareTo(nomeLido) == 0)
return true;
} catch (Exception exc) {
System.out.println("Exceção: " + exc.getMessage());
}
return false;
}
}
class ComparadorNome implements RecordComparator {
public int compare(byte[] reg1, byte[] reg2){
try {
ByteArrayInputStream BAIS = new ByteArrayInputStream(reg1);
DataInputStream DIS = new DataInputStream(BAIS);
String nome1 = DIS.readUTF();
DIS.close();
BAIS.close();
ByteArrayInputStream BAIS2 = new ByteArrayInputStream(reg2);
DataInputStream DIS2 = new DataInputStream(BAIS2);
String nome2 = DIS2.readUTF();
DIS2.close();
BAIS2.close();
if (nome1.compareTo(nome2) < 0) {
return PRECEDES;
} if (nome1.compareTo(nome2) > 0) {
return FOLLOWS;
}
} catch (Exception exc) {
System.out.println("Exceção: " + exc.getMessage());
}
return EQUIVALENT;
}
}
class Nomes {
private String nome, telefone;
private int recordId;
public Nomes(String nome, String telefone, int tipo, int recordId, int posicao) {
this.nome = nome;
this.telefone = telefone;
this.recordId = recordId;
}
public String getNome() {
return nome;
}
public String getTelefone() {
return telefone;
}
public void setNome(String nome) {
this.nome = nome;
}
public void setTelefone(String telefone) {
this.telefone = telefone;
}
public int getRecordId() {
return recordId;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment