Wednesday, May 22, 2013

Addition or Substraction of Double Values in Java


In subtracting one double from another, namely 45.32 - 45.31, I get a
result of 0.00999999999999801. According to all the math I've ever 
learned, the answer should be .01. Now the answer is:

double x = 45.32;
double y = 45.31;
double answer = (x - y);
answer = Math.round(answer*100)/100.0d; 

Monday, May 20, 2013

Groovy Grails Domain GORM and enum types


Create an enum class in src/groovy or src/java.

/**
 * User: pritom
 */
public enum UserStatus {
    active('active'),
    on_hold('on_hold')

    String name

    UserStatus(String name) {
        this.name = name
    }

    public String getName() {
        name
    }

    public String toString() {
        return this.getName()
    }
}

Specify a property in your domain class with the enum type.

class User {
 String userName,
 UserStatus type = UserStatus.active
}

Wednesday, May 8, 2013

Building a J2ME sliding menu with text and images

This example will show, how to create an image icon to perform the next action or next image from the list every time it's been clicked. So if you want to go from one icon to another icon by the nice sliding effect, you have to run the given example. For developing this application we have inherit canvass class and implement Runnable Interface. The Runnable interface is called from java.lang package and this interface has only one methods which is called: run() method. The function to run the application is as follows which is used in this application:

 

Use SlideMenuRunnable as following code:

display.setCurrent(new SlideMenuRunnable(Main Midlet Class Reference));

 

SlideMenuRunnable Class


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package the.contact.space;

import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;

/**
 *
 * @author User
 */
public class SlideMenuRunnable extends Canvas implements Runnable,CommandListener {
    SlideMenu menu = null;
    private Command cmdBack;
    private Home midlet;
    
    public SlideMenuRunnable(Home midlet){
        this.midlet = midlet;
        cmdBack = new Command("Back", Command.BACK, 1);
        addCommand(cmdBack);
        setCommandListener(this);
        Image[] image = new Image[3]; 
        try{
            image[0] = Image.createImage("/hk1.jpg");
            image[1] = Image.createImage("/hk2.jpg");
            image[2] = Image.createImage("/hk3.jpg");

            menu = new SlideMenu(new String[]{"1", "2", "3"},  
                image,  getWidth(),  getHeight());
            new Thread(this).start();
        }catch(Exception e){
            e.printStackTrace();
        }
    }
    
    protected void paint(Graphics g) {
        menu.paint(g);
    }
    
    public void keyPressed(int key){
        int gameKey = getGameAction(key);
        if(gameKey == Canvas.RIGHT){
            menu.slideItem(1);
        }else if(gameKey == Canvas.LEFT){
            menu.slideItem(- 1);
        }
    }

    public void run() {
        try{
            while(true){
                repaint();
                synchronized(this){
                    wait(100L);
                }
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }    

    public void commandAction(Command c, Displayable d) {
        if (c == cmdBack) {
            /* back code here */
        }
    }
}

SlideMenu Class

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package the.contact.space;

import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;

/**
 *
 * @author User
 */
public class SlideMenu {
    public int select_index, back_index, width, height;
    public Image r_arrow, l_arrow;
    String[] labels = null;
    Image[] icons = null;
    public int duration = 500;
    long time = 0;
    
    public SlideMenu(String[] labels, Image[] icons, int width, int height) throws Exception{
        try{
            r_arrow = Image.createImage("/right_arrow.png");
            l_arrow = Image.createImage("/left_arrow.png");
        }catch(Exception e){
            e.printStackTrace();
        }
        this.width = width;
        this.height = height;  
        this.labels = labels;
        this.icons = icons;  
    }
    
    public void slideItem(int next){
        if(!isImage() && select_index + next >= 0 && select_index + next < labels.length){
            back_index = select_index;  
            select_index += next;  
            time = System.currentTimeMillis();
        }
    }

    public boolean isImage(){
      return back_index != select_index;
    }

    public void paint(Graphics g){  
        g.setColor(255, 0, 0);
        g.fillRect(0, 0, width, height);  
        g.setColor(0, 0, 255);
  
        if(select_index > 0){
            g.drawImage(l_arrow, 2, height / 2, 
            Graphics.LEFT | Graphics.VCENTER);
        }

        if(select_index < icons.length - 1){
            g.drawImage(r_arrow, width - 2, height / 2, 
            Graphics.RIGHT | Graphics.VCENTER);
        }

        g.drawString(labels[select_index], width / 2, 
        height - 2, Graphics.BOTTOM | Graphics.HCENTER);  

        g.setClip(l_arrow.getWidth(), 0, width - 2 * 
        l_arrow.getWidth(), height);

        if(select_index != back_index) {
            int difference = (int)(System.currentTimeMillis() - time);  
            if(difference > duration){
                difference = duration;
            }

            int image_present = select_index > back_index ? 1 : - 1;
            int current_image = width / 2 - image_present * 
            difference * width / duration;

            int next_image = current_image + width * image_present;

            g.drawImage(icons[back_index], current_image, height / 2, 
            Graphics.VCENTER | Graphics.HCENTER);  

            g.drawImage(icons[select_index], next_image, height / 2, 
            Graphics.VCENTER | Graphics.HCENTER);

            if(difference >= duration){
                back_index = select_index;
            }
        } else {
            g.drawImage(icons[select_index], width / 2, height / 2, 
            Graphics.VCENTER | Graphics.HCENTER);
        }
    }
} 
http://www.roseindia.net/j2me/slide-image.shtml 

Where do I put images in J2me application

create a folder ( res) in your main project . 
put all images in this folder. 

add this folder in resource ..  by right clicking on resource folder from project browser and click add folder.

you can create images .. like 

Image image = createImage("/image.png")

Monday, May 6, 2013

View contact list using j2me


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package the.contact.space;

import java.util.Enumeration;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.List;
import javax.microedition.pim.Contact;
import javax.microedition.pim.ContactList;
import javax.microedition.pim.PIM;
import javax.microedition.pim.PIMList;

/**
 * @author User
 */
public class ViewContactList extends Form implements CommandListener {
    private final Home midlet;
    private Command cmdBack;
    private Enumeration contacts;
    private List contactList;
    private ContactList contList;

    /**
     *
     */
    public ViewContactList(String title, Home midlet) {
        super(title);
        this.midlet = midlet;
        cmdBack = new Command("Back", Command.BACK, 1);
        addCommand(cmdBack);
        setCommandListener(this);
        contactList = new List("Contact List", List.IMPLICIT);
        viewContactList2();
    }
    
    private void viewContactList2() {
        try {
            PIM pimInst = PIM.getInstance();
            contList = (ContactList) pimInst.openPIMList(PIM.CONTACT_LIST, PIM.READ_ONLY);
            contacts = contList.items();
            while (contacts.hasMoreElements()) {
                Contact tCont = (Contact) contacts.nextElement();
                String[] nameValues = tCont.getStringArray(Contact.NAME, 0);
                String firstName = nameValues[Contact.NAME_GIVEN];
                String lastName = nameValues[Contact.NAME_FAMILY];
                String phone = tCont.getString(Contact.TEL, 0);
                String email = null;
                try {
                    email = tCont.getString(Contact.EMAIL, 0);
                } catch (Exception ex) {}
                contactList.append(firstName + " " + lastName + "\n" + phone, null);
            }
            contactList.addCommand(cmdBack);
            contactList.setCommandListener(this);
            this.midlet.getDisplay().setCurrent(contactList);
        } catch (Exception ex) {
            ex.printStackTrace();
            Alert error = new Alert("Error", "No available contacts."+ex.getMessage(), null, AlertType.ERROR);
            error.setTimeout(Alert.FOREVER);
            this.midlet.getDisplay().setCurrent(error);
            return;
        }
    }
    
    public void commandAction(Command c, Displayable d) {
        if (c == cmdBack) {
            midlet.displayMainMIDlet();
        }
    }
}

Get event click list item in J2ME

In midp a list is actually more like a menu with a selection of choices. You have to set a command on it, so that in your command action you can dispatch on this command, get the selection form the menu and set the next screen accordingly.

package com.pkm;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.Choice;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.List;
import javax.microedition.lcdui.TextField;
import javax.microedition.midlet.*;

/**
 * @author User
 */
public class HelloMIDlet extends MIDlet implements javax.microedition.lcdui.CommandListener {
    private Display display;
    
    private Form form = new Form("Sign In Please");
    
    private Command submit = new Command("Submit", Command.SCREEN, 1);
    private Command exit = new Command("Exit", Command.EXIT, 1);
    private Command contactList = new Command("contactList", Command.OK, 1);
    private Command selection=new Command("Select", Command.ITEM, 1);
    
    List services;
    
    private TextField userName = new TextField("First Name:", "", 50, TextField.ANY);
    private TextField password = new TextField("Password", "", 30, TextField.PASSWORD);

    public HelloMIDlet() {
        display = Display.getDisplay(this);
        form.addCommand(submit);
        form.addCommand(exit);
        form.append(userName);
        form.append(password);
        form.setCommandListener(this);
    }

    public void startApp() {
        display.setCurrent(form);
    }

    public void pauseApp() {
    }

    public void destroyApp(boolean unconditional) {
    }

    public void commandAction(Command command, Displayable displayable) {
        if (command == submit) {
            validateUser(userName.getString(), password.getString());
        } else if (command == exit) {
            destroyApp(false);
            notifyDestroyed();
        } else if (command == contactList) {
            ContactList contactList = new ContactList("Contact List", this);
            display.setCurrent(contactList);
        } else if (command == selection) {
            int index = services.getSelectedIndex();
            Alert alert = new Alert("Your selection",
            "You chose " + services.getString(index) + ".",
            null, AlertType.INFO);
            Display.getDisplay(this).setCurrent(alert, services);
        }
    }
    
    public void validateUser(String name, String password) {
        if (name.equals("a") && password.equals("a")) {
            menu();
        } else {
            tryAgain();
        }
    }
    
    public void menu() {
        services = new List("Choose one", List.IMPLICIT);
        services.append("Check Mail", null);
        services.append("Compose", null);
        services.append("Addresses", null);
        services.append("Options", null);
        services.append("Sign Out", null);
        services.setSelectCommand(selection);
        services.addCommand(contactList);
        services.setCommandListener(this);
        
        display.setCurrent(services);
    }

    public void tryAgain() {
        Alert error = new Alert("Login Incorrect", "Please try again", null, AlertType.ERROR);
        error.setTimeout(Alert.FOREVER);
        userName.setString("");
        password.setString("");
        display.setCurrent(error, form);
    }

    void displayMainMIDlet() {
        menu();
    }
}

Sunday, May 5, 2013

ExtJS: HtmlEditor command list

The following list of commands is presented in alphabetical order. The commands may be mixed case or whatever makes your code more readable.
command value explanation / behavior
backcolor ???? This command will set the background color of the document.
bold none If there is no selection, the insertion point will set bold for subsequently typed characters.

If there is a selection and all of the characters are already bold, the bold will be removed.  Otherwise, all selected characters will become bold.
contentReadOnly true
false
This command will make the editor readonly (true) or editable (false).  Anticipated usage is for temporarily disabling input while something else is occurring elsewhere in the web page.
copy none If there is a selection, this command will copy the selection to the clipboard.  If there isn't a selection, nothing will happen.

note: this command won't work without setting a pref or using signed JS.  See: http://www.mozilla.org/editor/midasdemo/securityprefs.html

note:  the shortcut key will automatically trigger this command (typically accel-C) with or without the signed JS or any code on the page to handle it.
createlink url (href) This command will not do anything if no selection is made.  If there is a selection, a link will be inserted around the selection with the url parameter as the href of the link.
cut none If there is a selection, this command will copy the selection to the clipboard and remove the selection from the edit control.  If there isn't a selection, nothing will happen.

note: this command won't work without setting a pref or using signed JS.  See: http://www.mozilla.org/editor/midasdemo/securityprefs.html

note:  the shortcut key will automatically trigger this command (typically accel-X) with or without the signed JS or any code on the page to handle it.
decreasefontsize none This command will add a <small> tag around selection or at insertion point.
delete none This command will delete all text and objects that are selected.
fontname ???? This command will set the fontface for a selection or at the insertion point if there is no selection.
fontsize ???? This command will set the fontsize for a selection or at the insertion point if there is no selection.
forecolor ???? This command will set the text color of the selection or at the insertion point.
formatblock <h1>
<h2>
<h3>
<h4>
<h5>
<h6>
<pre>
<address>
<p>
p
[this list may not be complete]

heading <h1>
<h2>
<h3>
<h4>
<h5>
<h6>

hilitecolor ???? This command will set the hilite color of the selection or at the insertion point.  It only works with usecss enabled.
increasefontsize none This command will add a <big> tag around selection or at insertion point.
indent none Indent the block where the caret is located.
inserthorizontalrule none This command will insert a horizontal rule (line) at the insertion point.

Does it delete the selection?
inserthtml valid html string This command will insert the given html into the <body> in place of the current selection or at the caret location.
insertimage url (src) This command will insert an image (referenced by url) at the insertion point.

Does it delete the selection?
insertorderedlist none
insertunorderedlist none
insertparagraph none
italic none If there is no selection, the insertion point will set italic for subsequently typed characters.

If there is a selection and all of the characters are already italic, the italic will be removed.  Otherwise, all selected characters will become italic.
justifycenter none
justifyfull none
justifyleft none
justifyright none
outdent none Outdent the block where the caret is located.  If the block is not indented prior to calling outdent, nothing will happen.

note:  is an error thrown if no outdenting is done?
paste none This command will paste the contents of the clipboard at the location of the caret.  If there is a selection, it will be deleted prior to the insertion of the clipboard's contents.

note: this command won't work without setting a pref or using signed JS.
user_pref("capability.policy.policynames", "allowclipboard");
user_pref("capability.policy.allowclipboard.Clipboard.paste", "allAccess");

See: http://www.mozilla.org/editor/midasdemo/securityprefs.html

note:  the shortcut key will automatically trigger this command (typically accel-V) with or without the signed JS or any code on the page to handle it.
redo none This command will redo the previous undo action.  If undo was not the most recent action, this command will have no effect.

note:  the shortcut key will automatically trigger this command (typically accel-shift-Z)
removeformat none
selectall none This command will select all of the contents within the editable area.

note:  the shortcut key will automatically trigger this command (typically accel-A)
strikethrough none If there is no selection, the insertion point will set strikethrough for subsequently typed characters.

If there is a selection and all of the characters are already striked, the strikethrough will be removed. Otherwise, all selected characters will have a line drawn through them.
styleWithCSS true
false
This command is used for toggling the format of generated content.  By default (at least today), this is true.  An example of the differences is that the "bold" command will generate <b> if the styleWithCSS command is false and generate css style attribute if the styleWithCSS command is true.
subscript none If there is no selection, the insertion point will set subscript for subsequently typed characters.

If there is a selection and all of the characters are already subscripted, the subscript will be removed.  Otherwise, all selected characters will be drawn slightly lower than normal text.
superscript none If there is no selection, the insertion point will set superscript for subsequently typed characters.

If there is a selection and all of the characters are already superscripted, the superscript will be removed.  Otherwise, all selected characters will be drawn slightly higher than normal text.
underline none If there is no selection, the insertion point will set underline for subsequently typed characters.

If there is a selection and all of the characters are already underlined, the underline will be removed.  Otherwise, all selected characters will become underlined.
undo none This command will undo the previous action.  If no action has occurred in the document, then this command will have no effect.

note:  the shortcut key will automatically trigger this command (typically accel-Z)
unlink none