Mostrando entradas con la etiqueta Code. Mostrar todas las entradas
Mostrando entradas con la etiqueta Code. Mostrar todas las entradas

domingo, 21 de febrero de 2010

Odenando una coleción desde hibernate para un componente flex

Estaba programando un procedimiento remoto en java, usando hibernate. Que recupera una tabla anidada desde la base de datos para poblar un menú (mx.control.MenuBar). Por lo que el orden de los items es importante.

Agregando la opción order-by="atributoParaOrdenar" al archivo de mapping de la tabla, funciona bien solo del lado del servidor, pero los items en el componente aparece completamente desordenado (Los items de un mismo mivel). Lo que puede parecer natural, ya que el mapeo por defecto es de un java.util.Set de Java a un mx.collections.ArrayCollection de AS3.

Para corregir el asunto agregué el atributo sort="natural" al archivo de mapping. ej
<set name="children" inverse="true" lazy="false" table="menuitem" fetch="select" order-by="orden" sort="natural">
Luego la entidad java debe implementar la interfaz java.lang.Comparable y declarar la colección como un java.util.SortedSet. ej

private SortedSet children = new TreeSet();

con sus respectivos getters y setters.

Y re-escribir el algoritmo de ordenamiento para esta entidad. ej:
@Override
public int compareTo(Menuitem o) {
return this.orden.compareTo(o.getOrden());
}


Con esto ya aparecerá ordenado el el componente
















referencia

lunes, 15 de diciembre de 2008

Programa para determinar la compañía de un movil (Chile)

Aprovechando el insomnio de la noche del sábado, me he puse a programar una pequeña aplicación java para el celular, en éste al ingresar un número telefónico me indica a qué compañía pertenece (en Chile), y con esto también me dejo de andar preguntado "oye de qué compañía es tu móvil ?":) .
Por ahí anda otra aplicación que hace lo mismo, pero no me permitía seleccionar el número de mi agenda :(
Bueno sin más aquí dejo programa, solo tienen que copiar el archivo ComChile.jar al móvil y ejecutarlo ahí.
Además adjunto el código fuente.
Cualquier crítica, sugerencia o comentario será bienvenido.

Descargar programa

Fuente

Acá la clase principal:
/*  ComChile v1.1
* ------------------
* Copyright (C) 2008, René Vielma M. renevielma@gmail.com.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Library General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/

package pkg;


import java.io.IOException;
import java.io.InputStream;

import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.ImageItem;
import javax.microedition.lcdui.Item;
import javax.microedition.lcdui.ItemStateListener;
import javax.microedition.lcdui.TextField;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;


/**
* ComChile
* @author rene
*/
public class ComChile extends MIDlet implements ItemStateListener,CommandListener {

private Command salir, limpiar, about;
private Display display;
private Form formulario;
private TextField txt;
private Image imgClaro, imgMovistar, imgEntel;
private ImageItem imagenItem;

public ComChile() {

display = Display.getDisplay(this);

formulario = new Form("ComChile");

//Carga de imagen
try {
imgClaro = Image.createImage("/claro.jpg");
imgMovistar = Image.createImage("/movistar.jpg");
imgEntel = Image.createImage("/entel.jpg");
} catch (IOException e) {
e.printStackTrace();
}

salir = new Command("Salir", Command.EXIT, 1);
about = new Command("about", Command.HELP, 3);
limpiar = new Command("Limpiar", Command.OK, 0);
txt = new TextField("Número telefónico",null,20,TextField.PHONENUMBER);
imagenItem = new ImageItem(null,null ,Item.LAYOUT_CENTER,"no está la imagen",Item.BUTTON);

formulario.append(txt);

formulario.addCommand(salir);
formulario.addCommand(limpiar);
formulario.addCommand(about);
formulario.setCommandListener(this);
formulario.setItemStateListener(this);

}

protected void destroyApp(boolean arg0) throws MIDletStateChangeException {}

protected void pauseApp() {}

protected void startApp() throws MIDletStateChangeException {
display.setCurrent(formulario);
}

public void commandAction(Command c, Displayable s) {

if (c.getCommandType() == Command.EXIT)
notifyDestroyed();

if(c == limpiar){
txt.setString("");
if(formulario.size() == 2)
formulario.delete(1);
}

if(c == about){
Alert alert = new Alert("About", "ComChile v1.1 autor: Rene Vielma M.", null,AlertType.INFO);
Display.getDisplay(this).setCurrent(alert);
}
}

public void itemStateChanged(Item i){
if(i == txt){
if(formulario.size() == 2)
formulario.delete(1);

if(txt.getString().length() == 8 || (txt.getString().length() == 12) && txt.getString().substring(0, 4).equals("+569")){
System.out.println(txt.getString());
String num = (txt.getString().length() == 12 )?txt.getString().substring(4):txt.getString();

char c = buscarCom(num.substring(0, 4));

if(c == 'T'){
imagenItem.setImage(imgMovistar);
formulario.append(imagenItem);
}
if(c == 'E'){
imagenItem.setImage(imgEntel);
formulario.append(imagenItem);
}
if(c == 'C'){
imagenItem.setImage(imgClaro);
formulario.append(imagenItem);
}
}
}
}

public char buscarCom(String num){
try {
InputStream in = getClass().getResourceAsStream("/datos.txt");

StringBuffer sb = new StringBuffer();

int ch;
while ((ch = in.read()) != -1){
if((char)ch == '\n'){
if(num.equals(sb.toString().substring(0, 4))){
in.close();
return sb.charAt(4);
}
sb = new StringBuffer();
}else{
sb.append((char)ch);
}
}

in.close();

} catch (Exception e) {
Alert alert = new Alert("Error!", "No se pudo acceder al archivo de datos", null,AlertType.ERROR);
alert.setTimeout(Alert.FOREVER);
Display.getDisplay(this).setCurrent(alert);
}
return 'x';
}
}