All pastes #956514 Raw Edit

Predictive text entry

public java v1 · immutable
#956514 ·published 2008-03-25 11:18 UTC
rendered paste body
// MY CANVAS CLASSimport java.io.IOException;import javax.microedition.lcdui.game.GameCanvas;import javax.microedition.lcdui.Graphics;import javax.microedition.lcdui.*;import java.util.*;import javax.microedition.rms.RecordStoreException;/** * @author Ed's */public class MyCanvas extends GameCanvas {    public String[] keys = regularKey;     public static final String[] regularKey =     {".?!,@`-_:;()&\'\"~10$+x*/\\|[]=<>#","abc", "def", "ghi", "jkl",    "mno", "pqrs", "tuv", "wxyz"};    public static final String[] capitalKey =     {".?!,@`-_:;()&\'\"~10$+x*/\\|[]=<>#","ABC", "DEF", "GHI", "JKL",    "MNO", "PQRS", "TUV", "WXYZ"};    public static final String[] numbKey = {"1,2,3,4,5,6,7,8,9"};        StringBuffer width = new StringBuffer();    public StringBuffer sms;    // hold the whole sms text    public StringBuffer word; //hold the current typed, per word basis, new buffer created to replace the old one if space pressed        public static wordRS db;    Timer keyTimer;    Vector suggestedVector;        public static char ch;    public boolean keypress=false;    public boolean capital;    public boolean diffrentKey;    public char last;    public boolean dontPrint=true; //dont print if timerTask callling confirmPaint or it is at begining of the text    public boolean first; //first char entered    public boolean enteredNew=false; // if the entered is new word    public boolean sBoxAppeared=false;    public boolean notPrintingSuggestion=true;    public boolean notInDatabase=false; //if true the queried word not in the database until space pressed it will stay true                String currentIndicator="abc";    String oneWord; // word string buffer that has been converted to string                int countPress=0;    int zeroPress=0;    int sWordIndex=0;    public int counter=-1;    int index=-1;    int print=0;    int white_space=6;           //var for draw rect    int x, y;        int baseline=10;    int y_axis=12;    int line=1;        String justPressed;    int prevPressed;    char prevChar;        Font font;    public long time;    private int selection_speed=150;    private int red=0,green=0,blue=255;    private int back_red=250,back_green=250,back_blue=250;    Form menu;    public MyCanvas(){        super(false);        first=true; //       this.main=main;        sms=new StringBuffer();        word= new StringBuffer();        Graphics g=getGraphics();        font=Font.getFont(Font.FACE_PROPORTIONAL,Font.STYLE_BOLD,Font.SIZE_LARGE);        keyTimer = new Timer ();        keyTimer.schedule (new timerTask (this),500, selection_speed);                drawIndicator(currentIndicator);        try{db = new wordRS();} catch(RecordStoreException rse){rse.printStackTrace();}        }    public void submitQuery(){        if(!notInDatabase){                    try{            suggestedVector = db.getSuggestion(oneWord);        }        catch(RecordStoreException rse){            rse.printStackTrace();        }                if(suggestedVector.size()>0){            drawSBox(); //call the draw box & and draw the suggested Suggested word.            sBoxAppeared=true;//sBoxAppear=true            drawSWords();        }        else{            notInDatabase=true; //set booleean to indicate that the word is not exsisted in the database        }        }            }       public boolean notBegining(){       if(baseline == 10 && line == 1){return false;}       else {return true;}   }        public void drawIndicator(String indicator){        Font f = Font.getFont(Font.FACE_SYSTEM, Font.STYLE_ITALIC, Font.SIZE_SMALL);        Graphics g = getGraphics();        g.setFont(f);        int x= getWidth()-20;        g.setColor(back_red,back_green,back_blue);        g.fillRect(x,2,15,10);        g.setColor(20,20,20);        g.drawString(indicator, x, 2, g.TOP|g.LEFT);    }                public void addNewWord(){        if(word.length()>0){ //only when the word buffer is not empty            try {                db.addRecord(oneWord);                              }            catch (RecordStoreException ex) {ex.printStackTrace();}            catch (IOException ex) {ex.printStackTrace();}        }    }        public void delFromWord(){        if(word.length()>0){        word.deleteCharAt(word.length()-1);        oneWord = word.toString();        }    }        public void callPaint(char ch){        drawIndicator(currentIndicator);        Graphics g= getGraphics();        g.setColor(back_red,back_green,back_blue);        if(first){            g.fillRect(0,0,getWidth(),getHeight());            reset();            redrawAll();            first=false;            }        //baseline -1 so that i can cover the pointer        g.fillRect(baseline-1,y_axis,font.charWidth(this.last)+3,font.getHeight());        g.setColor(red,green,blue);        g.setFont(font);        g.drawChar(ch,baseline,line*24,g.LEFT|g.BASELINE);        flushGraphics();        }    public void showPointer(){        Graphics g = getGraphics();        g.setColor(0,0,0);        g.drawLine(baseline,y_axis,baseline,2*line*12);        flushGraphics();        }    //pointer appear //pointer disappear-use white line so that it cover the pointer line    public void hidePointer(){        Graphics g = getGraphics();        g.setColor(back_red,back_green,back_blue);        g.drawLine(baseline,y_axis,baseline,2*line*12);        flushGraphics();        }    //draw the selected    public void ConfirmPaint(char ch){        Graphics g = getGraphics();        sms.append(ch);        if(notPrintingSuggestion){addToWord();} //ad the char to the string buffer that holds the word        g.setColor(red,green,blue);        g.setFont(font);        g.drawChar(ch,baseline,line*24,g.LEFT|g.BASELINE); //draw the selected        baseline+=font.charWidth(ch); // so that the nect letter won't be drawn on the same position        if(baseline>getWidth()-30){     //move to the next line            width.append((char)baseline);            baseline=10;y_axis+=24;            line+=1;            }        flushGraphics();        if(sms.charAt(sms.length()-1)==' '){submitQuery();}                }        public void addToWord(){        word.append(ch);        oneWord = word.toString();    }        public void drawSelectedSuggestion(int Index){        notPrintingSuggestion=false;        StringBuffer selectedWord = (StringBuffer) suggestedVector.elementAt(Index);            for(int i= word.length(); i<=selectedWord.length(); i++){            char sChar = selectedWord.charAt(i-1);            ConfirmPaint(sChar);         }        notPrintingSuggestion=true;    }    public synchronized void deleteChar(){        if(sms.charAt(sms.length()-1)==' '){ //if the previous character is space            baseline-=white_space;    //        Graphics g= getGraphics();  //          g.setColor(back_red,back_green,back_blue);    //        g.fillRect(baseline,y_axis,font.charWidth(sms.charAt(sms.length()-1))+2,font.getHeight());            sms.deleteCharAt(sms.length()-1);            delFromWord();            }        else{            baseline-=font.charWidth(sms.charAt(sms.length()-1));            Graphics g= getGraphics();            g.setColor(back_red,back_green,back_blue);            g.fillRect(baseline,y_axis,font.charWidth(sms.charAt(sms.length()-1))+2,font.getHeight());            delFromWord();            }        flushGraphics();    }        public void redraw(char ch ){        Graphics g= getGraphics();        g.setColor(red,green,blue);        g.setFont(font);        g.drawChar(ch,baseline,line*24,g.LEFT|g.BASELINE);        baseline+=font.charWidth(ch);        if(baseline>getWidth()-30){            width.append((char)baseline);            baseline=10;y_axis+=24;            line+=1;        }        flushGraphics();        }    public void reset(){        if(width.length() >0)        width.delete(0,width.length()-1);        line=1;        baseline=10;y_axis=12;        }    public void redrawAll(){        Graphics g=getGraphics();        g.setColor(back_red,back_green,back_blue);        g.fillRect(0,0,getWidth(),getHeight());        reset();        for(int a=0;a<sms.length();a++)        redraw(sms.charAt(a));        }        public void drawSBox(){        Graphics g = getGraphics();        g.setColor(0,0,0);        x=getWidth()/2-getWidth()/6;        y=y_axis+20;        g.drawRect(x , y, getWidth()/3, font.getHeight()*5+40);        sBoxAppeared=true;        flushGraphics();    }    public void hideSBox(){        Graphics g = getGraphics();        g.setColor(back_red,back_green,back_blue);        x=getWidth()/2-getWidth()/6;        y=y_axis+20;        g.fillRect(x , y, getWidth()/3, font.getHeight()*5+40);        sBoxAppeared=false;        flushGraphics();    }        public void drawSWords(){        int X= x+5;        int Y= y+4;        Graphics g = getGraphics();        g.setColor(red, green, blue);        for(int i=0; i<5; i++){            g.drawString((i+1)+(String)suggestedVector.elementAt(i), X, Y, g.BASELINE|g.HCENTER);            Y=Y+10;        }    }        public synchronized void keyPressed (int keyCode) {        hideSBox();// if user keep preessing without choosing hide the suggestionBox        time=System.currentTimeMillis(); // record the time when the keypress is pressed        index=keyCode-49; // -49 is for motorola phone keycode, but it works fine on the standard emulator too             if(keyCode==-8){ //-8 is keycode for clear button  DELETE CHAR (does not delete properly ????)                        if(sms.length()>0){                hidePointer();                if(baseline<=10){                    System.out.println(baseline);                    line-=2;                    baseline=(int)width.charAt(line);                    line++;                    y_axis-=24;                    }                deleteChar();            }           }                if(keyCode==35){//35 is the keycode for SPACE button (still having problem it only works properly when users wait for timeout)                if(notBegining()){                hidePointer();                sms.append(" ");                baseline+=white_space;                 prevPressed=keyCode;                showPointer();                if(notInDatabase){addNewWord();}                notInDatabase=false;                word = new StringBuffer(); //if space just pressed reset the buffer coz the next letter should be belong to new word                }          }                                          else{                           //ACCEPTING USER KEYPRESS TO SELECT THE SUGGESTED WORD --START            if(sBoxAppeared){  //executed only when the suggestion box appear                drawSelectedSuggestion(index);                db.updateFrequency(index);                sBoxAppeared=false;                word = new StringBuffer();            }//ACCEPTING USER KEYPRESS TO SELECT THE SUGGESTED WORD --STOP*/                    if(keyCode == prevPressed || dontPrint){ //dontPrint: timerTask has excecuted confirmpaint so counterPress has to be reseted            keypress=true;            int limit = setLimit(index);            if(dontPrint){countPress=limit+1;}            if(countPress<limit){                MyCanvas.ch=keys[index].charAt(countPress);                callPaint(MyCanvas.ch);                countPress++;            }            else{                 countPress=0;                    MyCanvas.ch=keys[index].charAt(countPress);                 callPaint(MyCanvas.ch);                 countPress++;                  }            dontPrint=false;            }        else{ //this is executed when the key is not repeated (prev!=)              ConfirmPaint(last);             countPress=0;                MyCanvas.ch=keys[index].charAt(countPress);             callPaint(MyCanvas.ch);             countPress++;             }                  }                last=MyCanvas.ch;        prevPressed=keyCode;          }    public int setLimit(int index){ //limit is do determine the last element of the String array "KEY"    int limit = 0;     if(index==0){limit=34;}    if((index>=1 && index <=5) || index==7){ limit=3;}    if(index==6 || index==8){ limit=4;}    return limit;}        public void closeDB() throws RecordStoreException    {db.closeRS();}//this method destroy the enumeration and close the database  }wordRS CLASSimport java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.DataInputStream;import java.io.DataOutputStream;import java.io.IOException;import java.util.Vector;import javax.microedition.rms.RecordEnumeration;import javax.microedition.rms.RecordStore;import javax.microedition.rms.RecordStoreException;import javax.microedition.rms.RecordStoreNotOpenException;/** * * @author Ed's */public class wordRS {        private RecordStore rs;    RecordEnumeration re;    private Vector suggestions;    private Vector suggestionsID;    private Vector suggestionsFreq;//    private String query;        public wordRS() throws RecordStoreException{        rs=RecordStore.openRecordStore("recordStore", true);    }        public void closeRS() throws RecordStoreException{        try{            re.destroy();            rs.closeRecordStore();        }        catch(RecordStoreNotOpenException rsnoe){            rsnoe.printStackTrace();        }    }            public void addRecord(String newWord) throws RecordStoreException, IOException{        ByteArrayOutputStream BO = new ByteArrayOutputStream();        DataOutputStream DO = new DataOutputStream(BO);                try{            DO.writeUTF(newWord);            DO.writeInt(1);        }        catch (IOException ioe){            ioe.printStackTrace();                    }                rs.addRecord(BO.toByteArray(), 0, BO.toByteArray().length);        DO.close();        BO.close();    }            public Vector getSuggestion(String query){        try{            MatchFilter filter = new MatchFilter(query);            Sorter sort = new Sorter();            re = rs.enumerateRecords(filter, sort, true);            ByteArrayInputStream b = null;            DataInputStream d = null;            String suggestedWord;            String suggestedFreq;            while(re.hasNextElement()){                byte [] record = re.nextRecord();                String recID = String.valueOf(re.nextRecordId());                b = new ByteArrayInputStream(record);                d = new DataInputStream(b);                suggestedWord = d.readUTF();                suggestedFreq = String.valueOf(d.readInt());                suggestions.addElement(suggestedWord); //put the word to vector                suggestionsID.addElement(recID); //put the rec id to vector                suggestionsFreq.addElement(suggestedFreq);                }                        b.close();            d.close();                    }        catch(RecordStoreException rse){            rse.printStackTrace();        }        catch(IOException ioe){            ioe.printStackTrace();        }        return suggestions;    }         public void updateFrequency(int idIndex){        String recID = (String)suggestionsID.elementAt(idIndex);        String theWord = (String)suggestions.elementAt(idIndex);        String theInt = (String)suggestionsFreq.elementAt(idIndex);                ByteArrayOutputStream BO = new ByteArrayOutputStream();        DataOutputStream DO = new DataOutputStream(BO);                try{            DO.writeUTF(theWord);            DO.writeInt(Integer.parseInt(theInt)+1);                            try{ rs.addRecord(BO.toByteArray(), 0, BO.toByteArray().length);                rs.deleteRecord(Integer.parseInt(recID));            }            catch(RecordStoreException e){e.printStackTrace();}                        DO.close();            BO.close();        }            catch (IOException ioe){            ioe.printStackTrace();                    }    }}