3 Replies - 790 Views - Last Post: 30 September 2009 - 02:30 PM Rate Topic: -----

#1 nathanpc  Icon User is offline

  • SCIENCE!
  • member icon

Reputation: 112
  • View blog
  • Posts: 1,171
  • Joined: 31-July 09

Error When Using RecordStore With Java ME

Post icon  Posted 12 August 2009 - 03:36 PM

Hello,
I'm learning Java ME, remember that i'm already a Java developer, but i was trying to do a simple contact book application, then when it was finished i run it in the WTK emulator, but when i try to add some record it only shows me the message that i didn't wrote anything in the fields, but i wrote!, here is the GIF of the message:
Posted Image

And here is my code:
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, ItemStateListener {
	private Display display;
	private Alert alerta;
	private Form telainicial, adicionaReg;
	private TextField nome, telefone;
	private Command sair, adicionar, voltar, salvar, zerar;
	private RecordStore rs = null;
	String tipo, mensagem;
	boolean gravacaoOK = false;
	private ChoiceGroup tipo_contato;
	private String[] listaTipo = {"Amigos", "Família", "Trabalho", "Teste"};
	private Form listagemReg;
	private Command listar, apagar, ordenar, filtrar;
	private ChoiceGroup listaRegistros;
	boolean deletedFlags[] = null;
	private Vector vecNomes;
	
	public simplecontacts() {
		display = Display.getDisplay(this);
		sair = new Command("Sair", Command.EXIT, 0);
		adicionar = new Command("Adicionar Registros", Command.SCREEN, 1);
		zerar = new Command("Zerar Registros", Command.SCREEN, 1);
		voltar = new Command("Voltar", Command.SCREEN, 1);
		salvar = new Command("Salvar Registro", Command.SCREEN, 1);
		nome = new TextField("Nome:", "", 20, TextField.ANY);
		telefone = new TextField("Telefone:", "", 10, TextField.PHONENUMBER);
		listar = new Command("Listar Registros", Command.SCREEN, 1);
		listaRegistros = new ChoiceGroup("Registros", ChoiceGroup.MULTIPLE);
		vecNomes = new Vector();
		apagar = new Command("Apagar Registros", Command.SCREEN, 1);
		ordenar = new Command("Ordenar Registros", Command.SCREEN, 1);
		filtrar = new Command("Filtrar Registros", Command.SCREEN, 1);
		
		telainicial = new Form("Simple Contacts");
		telainicial.addCommand(sair);
		telainicial.addCommand(adicionar);
		telainicial.addCommand(zerar);
		telainicial.addCommand(listar);
		telainicial.addCommand(ordenar);
		telainicial.addCommand(filtrar);
		telainicial.addCommand(zerar);
		telainicial.setCommandListener(this);
		adicionaReg = new Form("Adiciona Contato");
		tipo_contato = new ChoiceGroup("Tipo do Contato", Choice.POPUP, listaTipo, null);
		adicionaReg.append(nome);
		adicionaReg.append(telefone);
		adicionaReg.append(tipo_contato);
		adicionaReg.addCommand(salvar);
		adicionaReg.addCommand(voltar);
		adicionaReg.setCommandListener(this);
		listagemReg = new Form("");
		listagemReg.append(listaRegistros);
		listagemReg.addCommand(apagar);
		listagemReg.addCommand(voltar);
		listagemReg.setItemStateListener(this);
		listagemReg.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(telainicial);
	}
	
	private void gerarTela(Vector nomes, int totalElementos) {
		for (int i = listaRegistros.size(); i > 0; i--)
			listaRegistros.delete(i - 1);
		for (int i = 0; i < nomes.size(); i++) {
			Nomes item = (Nomes) vecNomes.elementAt(i);
			String nome = item.getNome();
			String telefone = item.getTelefone();
			listaRegistros.append(nome + " " + telefone, null);
		}
		display.setCurrent(listagemReg);
	}
	
	private void listarRegistros(FiltroNome f, ComparadorNome c) {
		RecordEnumeration rEnum = null;
		vecNomes.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);
				vecNomes.addElement(itemAgenda);
				posicao++;
			}
			gerarTela(vecNomes, 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) vecNomes.elementAt(i);
					try {
						rs.deleteRecord(itemAgenda.getRecordId());
					} catch (Exception exc) {
					}
				}
			}
		display.setCurrent(telainicial);
	
		} 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(nome.getString());
			DOS.writeUTF(telefone.getString());
			DOS.writeInt(tipo_contato.getSelectedIndex());
			byte [] bRec = BAOS.toByteArray();
			rs.addRecord(bRec, 0, bRec.length);
			DOS.close();
			BAOS.close();
			display.setCurrent(telainicial);
		} 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(telainicial);
	}
	
	public void itemStateChanged (Item item) {		
		if (item instanceof TextField) {
			String teste = ((TextField)item).getString();
			if (teste != "") {
				gravacaoOK = true;
			}
		}
		
		if (item instanceof ChoiceGroup) {
			deletedFlags = new boolean[listaRegistros.size()];
			listaRegistros.getSelectedFlags(deletedFlags);
		}
	}
	
	public void commandAction(Command com, Displayable dis) {
		if (com == sair) {
			try {
				rs.closeRecordStore();
			} catch (Exception exc) {
				mostrarAlerta("Erro fechando o RecordStore -", exc.toString());
			}
			destroyApp(true);
		} else if (com == adicionar) {
			nome.setString("");
			telefone.setString("");
			display.setCurrent(adicionaReg);
		} else if (com == salvar) {
			if (gravacaoOK == false) {
				mostrarAlerta("Registro vazio não será salvo", "Tente Novamente");
			} else {
				adicionarRegistro();
			}
		} else if (com == zerar) {
			zerarRegistros();
		} else if (com == voltar) {
			display.setCurrent(telainicial);
		} else if (com == apagar) {
			apagarRegistros();
		} else if (com == listar) {
			listagemReg.setTitle("Listagem Geral");
			listaRegistros.deleteAll();
			listarRegistros(null, null);
		} else if (com == ordenar) {
			listagemReg.setTitle("Registros Ordenados");
			listaRegistros.deleteAll();
			ComparadorNome comparador = new ComparadorNome();
			listarRegistros(null, comparador);
		} else if (com == filtrar) {
			listagemReg.setTitle("Registros Filtrados");
			listaRegistros.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;
	}
}

What is Wrong?

Thanks,
Nathan Paulino Campos

This post has been edited by nathanpc: 12 August 2009 - 03:37 PM


Is This A Good Question/Topic? 0
  • +

Replies To: Error When Using RecordStore With Java ME

#2 nathanpc  Icon User is offline

  • SCIENCE!
  • member icon

Reputation: 112
  • View blog
  • Posts: 1,171
  • Joined: 31-July 09

Re: Error When Using RecordStore With Java ME

Posted 12 August 2009 - 05:37 PM

Please, someone help me!!!!!!!!!!!!!!
Was This Post Helpful? 0
  • +
  • -

#3 sherinfee  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 13
  • Joined: 27-June 09

Re: Error When Using RecordStore With Java ME

Posted 14 August 2009 - 02:02 PM

Hi,I think people are not much interested in Java ME!!,due to nobody answered my question in Java ME too!!
:crazy:
Was This Post Helpful? 0
  • +
  • -

#4 1234  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 4
  • Joined: 16-October 07

Re: Error When Using RecordStore With Java ME

Posted 30 September 2009 - 02:30 PM

Hey man you need convert telefone and nome for String
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1