0

Hello,
I'm learning Java ME, remember that i'm already a Java developer, but i want to create another form to show all the details of the contact, like that of the contact book of the cell phones, 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 {
	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;
	}
}

What i have to do?

Thanks,
Nathan Paulino Campos

2
Contributors
4
Replies
5
Views
8 Years
Discussion Span
Last Post by Nathan Campos
0

The application that i'm developing is a simple contact book and if you didn't understand very nice my previous post, i need to change my code, in the list registry's form an option that the user can select a contact, click in a Command and it redirect the user to another form that he can see the full details about that contact that he selected, like name, telephone and type.

Thanks!

0

Two options:
A) you pass Displayable object from form to form
B) or have "magic" method changeScreen to do the job as in this MIDlet

package contacts;

import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.midlet.MIDlet;

import memo.beans.Contact;

public class ContactMIDlet extends MIDlet{

    private Display display;

    public ContactMIDlet(){}

    public void startApp(){
        display = Display.getDisplay(this);
        changeScreen(CoreUI.MAIN_MENU);
    }

    public void pauseApp(){}

    public void destroyApp(boolean unconditional){}

    public void quitApp(){
        destroyApp(true);
        notifyDestroyed();
    }

    /**
     * Method to simplify movement from screen to screen
     * @param _uiClass specifies name of class to be used
     * as declared in the CoreUI interface
     */
    public void changeScreen(String _uiClass) {
        Displayable displayable;
        try {
            displayable = (Displayable) Class.forName(_uiClass).newInstance();
            ((CoreUI) displayable).setUIManager(this);
            display.setCurrent(displayable);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Overloaded method of changeScreen just pop-up any alerts as need it.
     * @param d
     */
    public void changeScreen(Displayable d){
        display.setCurrent(d);
    }

    public void changeScreen(String _uiClass, Contact contact) {
        Displayable displayable;
        try {
            displayable = (Displayable) Class.forName(_uiClass).newInstance();
            ((CoreUI) displayable).setUIManager(this, contact);

            display.setCurrent(displayable);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}

interface CoreUI

package contacts;

import memo.beans.Memo;

public interface CoreUI {

    public final String MAIN_MENU = "contact.gui.MainMenu";
    public final String CONTACT_FORM = "contact.gui.ContactForm";
    public final String VIEW_CONTACTS = "contact.gui.ViewContacts";
    public final String EDIT_CONTACT = "contact.gui.EditContact";

    void setUIManager(ContactMIDlet _mgr);

    void setUIManager(ContactMIDlet _mgr, Contact contact);
}

where EditContact can look like this for start

public class EditContact extends Form implements CoreUI, CommandListener {

    private ContactMIDlet mgr;
    private Contact contact;
    private Command backCommand,  exitCommand,  saveCommand;

    /**
     * Default constructor
     */
    public EditContact() {
        super("Add Contact");
    }

    public void setUIManager(ContactMIDlet _mgr) {}

    public void setUIManager(ContactMIDlet _mgr, Contact contact){
        this.mgr = _mgr;
        this.contact = contact;
        initScreen(); //Show the form
    }

    /**
     * Method to implement this form GUI
     */
    private void initScreen() {

    // REST OF THE CODE
    }
}
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.