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:
http://users.cjb.net/windows-ce/wtk-bug.gif

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

I tried to look at it, but the use of Spanish (I presume it is Spanish and not Italian or Portuguese) make it difficult. Add to it over 300 lines of code where one has no chance to find what is which screen, it is long period of time spend just figuring out what is what. If you can get at least methods names to English, it would be different story

PS: Don't want to hurt your feelings, but boasting about being Java developer and then provide this long code and with none comments says you either lying or you not a good programmer... Nothing personal dude

Hello Peter,
It's portuguese, because i'm from Brazil, i'm going to translate all the program if it's more simple to you.

Thanks,
Nathan Paulino Campos

If you do so, I'm more then happy to check it out again.

Hello Peter,
Now i've translated all the code to english, except the error messages, but the error message that shows me every time i've translated it, it is in the line 207, here is the 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 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.setItemStateListener(this);
		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 itemStateChanged (Item item) {		
		if (item instanceof TextField) {
			String teste = ((TextField)item).getString();
			if (teste != "") {
				recordOK = true;
			}
		}
		
		if (item instanceof ChoiceGroup) {
			deletedFlags = new boolean[listRegistrys.size()];
			listRegistrys.getSelectedFlags(deletedFlags);
		}
	}
	
	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) {
			if (recordOK == false) {
				mostrarAlerta("Empty registry didn't be saved", "Try Again");
			} else {
				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;
	}
}

Thanks,
Nathan Paulino Campos

Your validation process is not working. You are listening for changes on TextField, but you actually never associated this listener with textFields (only associated with ChoiceGroup on line 58). Therefore boolean recordOK will never change state from false to true.
You are overcomplicating your life with setting various listeners that you do not need. Simple solution, on save command call validation method that will have boolean return type and there check if user entered any data.
Also

String teste = ((TextField)item).getString();
if (teste != "") {

can be replaced by

String teste = ((TextField)item).getString();
if (teste.size() > 0) {

Make this changes and let me know if you still have any problems with this MIDlet.

Thanks Peter, but now i have an error in my code, it says this, in Eclipse:

The method size() is undefined for the type String

Here is the code:

public void itemStateChanged (Item item) {		
		if (item instanceof TextField) {
			String teste = ((TextField)item).getString();
			if (teste.size() > 0) {
				recordOK = true;
			}
		}

Thanks!

Remember that the alert of Try Again is occurring when i use length() instead of size().

Ooops size() was incorrect it should be lenght().

Did you attached ItemStateListener to TextFields?

As I said this

public void itemStateChanged (Item item) {		
		if (item instanceof TextField) {
			String teste = ((TextField)item).getString();
			if (teste.size() > 0) {
				recordOK = true;
			}
		}

can be replaced by simple validation method such as

private boolean validation(){
    if(name.getString().length() > 0 && telefone.getString().length() > 0){
        return true;
    }
    return false;
}
commented: Thanks very much!!!! +1

Thanks very much Peter!
+1 of reputation!

No problem.
If I can advise, try to split your MIDlet and move in classes specifically these dealing with GUI. You will have to write of-course more code, but it will be easier to debug and maintain

Thanks for the very nice tip!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.