J2ME MIDP4Palm reseting recordStore

Hi all,
I have a recordStore with many records in it. I have changed the way I pack and unpack my data aswell as some other small changes in my MIDlet.
The problem is:
I am getting 1 or 2 exceptions in my program. As a result of my MIDlet changing as I develop it, there are records in the recordStore that are not being read because the elements that each record holds has changed. I want to get rid of these "old" records and start off with a blank recordStore. These "old" records are throwing exceptions in my program making it very hard to debug!!
Any ideas??
Thanks,
Liam C

read the javadoc....
public static void deleteRecordStore(String recordStoreName)
throws RecordStoreException,
RecordStoreNotFoundExceptionDeletes the named record store. MIDlet suites are only allowed to operate on their own record stores, including deletions. If the record store is currently open by a MIDlet when this method is called, or if the named record store does not exist, a RecordStoreException will be thrown.
Parameters:
recordStoreName - the MIDlet suite unique record store to delete.
Throws:
RecordStoreException - if a record store-related exception occurred.
RecordStoreNotFoundException - if the record store could not be found.

Similar Messages

  • RMS file version

    Hello.
    When I create a Midlet with J2ME Wireless Toolkit I have noted that the -VM number of RMS file, used by program, sometimes change the value.
    Why?
    Best regards.

    1) Probably because the MIDP subsystem has some way of keeping track of RecordStore versions that is independent of the RecordStore instance itself.
    2) You don't do this. I'm not familiar with how J2ME works on Palm devices but I will tell you one think, if Palm J2ME system stores RecordStore objects as files accessible to the user, you should not access them directly but via the MIDP API. A common practice employed for a good reason :-)
    3) The only solution is to remove the RecordStore using some RMS management functionality and then create a new one.
    Remember, this is limited Java implementation and you should use the MIDP API to do all of your operations on RecordStores, it was designed to cover large spectrum of devices and for that reason limits functionality to a level that might seem quite restraining. The benefit is that you application will run on any MIDP compliant device. There is always a price to pay. If you are writing only for Palm I suggest you use the native Palm SDK.
    Regards Jirka

  • How to create an inbox for WMA sms?

    Hi,
    Please can anyone tell me how to create an inbox for the WMADemo that is used for sending and recieving sms. PLEASE HELP!!!

    For this you will need persistant storage. The only persistant storage available on J2ME devices are RecordStores. You'll probably need to use that.
    Everytime a message comes it, store it in the RMS, and only delete it if the user requests that op.

  • J2ME RMS and Palm OS

    I am trying to capture data entered by the users in RMS. I have no trouble doing so in the phone emulators of the J2ME Wireless Toolkit, but the Palm emulator does not save the data. I tried blocking flush()- as someone suggested to me, but no success. Can someone look at my code or give me some ideas? Thanks
    if (command == saveCommand) {
    String vt = vType.getString();
    int vtID = Integer.parseInt(vTypeID.getString());
    String shp = shape.getString();
    String mk = make.getString();
    try
    writeRecord(vt, mk, shp, vtID);
    public void writeRecord(String vt,String mk, String shp, int id)
    try
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    DataOutputStream dos = new DataOutputStream(baos);
    byte[] record;
    dos.writeUTF(vt);
    dos.writeUTF(mk);
    dos.writeUTF(shp);
    dos.writeInt(id);
    //dos.flush();
    record = baos.toByteArray();
    valveTypeStore.addRecord(record, 0, record.length);
    //baos.reset();
    baos.close();
    dos.close();

    did u call the closeRecordStore() method of RecordStore??

  • Problems in recordstore

    Hi all,
    I am completely new to java/j2me. I am trying to write and read to and from a recordstore. The problems that i am facing are
    1. If I add both the exit and start command then then none of the command works.
    2. If I comment out the exit command line then probably the data gets written into the recordstore but while reading it I print them then it only displays the integer as 0 instead of the value that was assigned to it.
    In the code I have marked out the problems I am facing
    import javax.microedition.rms.*;
    import javax.microedition.midlet.*;
    import javax.microedition.lcdui.*;
    import java.io.*;
    public class RecordStoreTest
    extends MIDlet implements CommandListener
    private Display display;
    private Alert alert;
    private Form form;
    private Command exit;
    private Command start;
    private RecordStore recordstore = null;
    private RecordEnumeration recordEnumeration = null;
    public RecordStoreTest()
    display = Display.getDisplay(this);
    exit = new Command("Exit", Command.SCREEN, 1);
    start = new Command("Start", Command.SCREEN, 1);
    form = new Form("Mixed Record");
    // If I uncomment the line below then none of the Commands work.
    //form.addCommand(exit);
    form.addCommand(start);
    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 == exit)
    destroyApp(true);
    notifyDestroyed();
    else if (command == start)
    try
    recordstore = RecordStore.openRecordStore("myRecordStore", true);
    catch(Exception error)
    alert = new Alert("Error Creating", error.toString(), null, AlertType.WARNING);
    alert.setTimeout(Alert.FOREVER);
    display.setCurrent(alert);
    try
    byte[] outputRecord;
    String outputString[] = { "ABC", "XYZ", "PQRS" , "UVW", "OTHERS"};
    int outputno[] = {1234, 1567, 1890, 1345, 1789};
    int outputval[] = {5000, 6000, 7000, 8000, 9000};
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    DataOutputStream outputDataStream = new DataOutputStream(outputStream);
    for(int x=0; x<5; x++)
    outputDataStream.writeInt(outputno[x]);
    outputDataStream.writeUTF(outputString[x]);
    outputDataStream.writeInt(outputval[x]);
    outputDataStream.flush();
    outputRecord = outputStream.toByteArray();
    recordstore.addRecord(outputRecord, 0, outputRecord.length);
    outputStream.reset();
    outputStream.close();
    outputDataStream.close();
    catch(Exception error)
    alert = new Alert("Error Writing", error.toString(),null,AlertType.WARNING);
    alert.setTimeout(Alert.FOREVER);
    display.setCurrent(alert);
    try
    StringBuffer buffer = new StringBuffer();
    byte[] byteInputData = new byte[300];
    ByteArrayInputStream inputStream = new ByteArrayInputStream(byteInputData);
    DataInputStream inputDataStream = new DataInputStream(inputStream);
    recordEnumeration = recordstore.enumerateRecords(null,null,false);
    while(recordEnumeration.hasNextElement())
    recordstore.getRecord(recordEnumeration.nextRecordId());
    // this line prints 0 not the data 1234 written in the recordstore.
    System.out.println("Data 1 is : " + inputDataStream.readInt());
    buffer.append(inputDataStream.readInt());
    buffer.append(" ");
    buffer.append(inputDataStream.readUTF());
    buffer.append(" ");
    buffer.append(inputDataStream.readInt());
    buffer.append(" ");
    catch(Exception error)
    alert = new Alert("Error Reading", error.toString(),null,AlertType.WARNING);
    alert.setTimeout(Alert.FOREVER);
    display.setCurrent(alert);
    Thanks a lot
    Ayan

    Hi Ayen
    Your 1st Problem I can find no reason for, I tested using Sun WTK25 and on a Nokia 6680 And The Start and exit buttons both worked.
    2nd Problem, You were not reading the records into your byte variable.
    I have changed the code - and it works on wtk25 and nokia 6680
    import javax.microedition.rms.*;
    import javax.microedition.midlet.*;
    import javax.microedition.lcdui.*;
    import java.io.*;
    public class RecordStoreTest
    extends MIDlet implements CommandListener
    private Display display;
    private Alert alert;
    private Form form;
    private Command exit;
    private Command start;
    private RecordStore recordstore = null;
    private RecordEnumeration recordEnumeration = null;
    public RecordStoreTest()
    display = Display.getDisplay(this);
    exit = new Command("Exit", Command.SCREEN, 1);
    start = new Command("Start", Command.SCREEN, 1);
    form = new Form("Mixed Record");
    // If I uncomment the line below then none of the Commands work.
    // I tested this using sun WTK 25 and a Nokia 6680 and it works correctly, what are you running the app on?
    form.addCommand(exit);
    form.addCommand(start);
    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 == exit)
    destroyApp(true);
    notifyDestroyed();
    else if (command == start)
    try
    recordstore = RecordStore.openRecordStore("myRecordStore", true);
    catch(Exception error)
    alert = new Alert("Error Creating", error.toString(), null, AlertType.WARNING);
    alert.setTimeout(Alert.FOREVER);
    display.setCurrent(alert);
    try
    byte[] outputRecord;
    String outputString[] = { "ABC", "XYZ", "PQRS" , "UVW", "OTHERS"};
    int outputno[] = {1234, 1567, 1890, 1345, 1789};
    int outputval[] = {5000, 6000, 7000, 8000, 9000};
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    DataOutputStream outputDataStream = new DataOutputStream(outputStream);
    for(int x=0; x<5; x++)
    outputDataStream.writeInt(outputno[x]);
    outputDataStream.writeUTF(outputString[x]);
    outputDataStream.writeInt(outputval[x]);
    outputDataStream.flush();
    outputRecord = outputStream.toByteArray();
    recordstore.addRecord(outputRecord, 0, outputRecord.length);
    outputStream.reset();
    outputStream.close();
    outputDataStream.close();
    catch(Exception error)
    alert = new Alert("Error Writing", error.toString(),null,AlertType.WARNING);
    alert.setTimeout(Alert.FOREVER);
    display.setCurrent(alert);
    try
    //StringBuffer buffer = new StringBuffer();
    String sbuffer="";
    byte[] byteInputData = new byte[300];
    ByteArrayInputStream inputStream = new ByteArrayInputStream(byteInputData);
    DataInputStream inputDataStream = new DataInputStream(inputStream);
    recordEnumeration = recordstore.enumerateRecords(null,null,false);
    while(recordEnumeration.hasNextElement())
    //You did not get your data into the byte variable
    recordstore.getRecord(recordEnumeration.nextRecordId(),byteInputData,0);
    //System.out.println("Data 1 is : " + inputDataStream.readInt());
    StringBuffer buffer = new StringBuffer();
    buffer.append(inputDataStream.readInt());
    buffer.append(" ");
    buffer.append(inputDataStream.readUTF());
    buffer.append(" ");
    buffer.append(inputDataStream.readInt());
    buffer.append(" ");
    System.out.println("Buffer=" + buffer);
    sbuffer=buffer.toString();
    form.append(sbuffer.trim() + "\n");
    catch(Exception error)
    alert = new Alert("Error Reading", error.toString(),null,AlertType.WARNING);
    alert.setTimeout(Alert.FOREVER);
    display.setCurrent(alert);
    Hope it helps
    Regards
    Steve

  • How to set up on device debuging with J2ME SDK 3.0 and window mobile 6.5?

    I got some infomation about setting up on device debuging in J2ME SDK 3.0 with real device(e.g samsung windown mobile B7330). When I start debuging on device, I got exception when open RMS
    javax.microedition.rms.RecordStoreException: error opening record store fileHere my code:
    public void saveProfile() {
            byte[] data = toByteArray();
            try {
                rs = RecordStore.openRecordStore("kunkunProfile", true);
                for (RecordEnumeration e = rs.enumerateRecords(null, null, false); e.hasNextElement();) {
                    int id = e.nextRecordId();
                    rs.deleteRecord(id);
                rs.addRecord(data, 0, data.length);
                rs.closeRecordStore();
            } catch (Exception ex) {
                System.out.println("Exception in OpenRecordStore..." + ex.getMessage());
                try {
                    rs.addRecord(data, 0, data.length);
                    rs.closeRecordStore();
                } catch (Exception e) {
                ex.printStackTrace();
        }Anybody help me? I am stuck here.

    Hi dominikg,
    At first, You can try to restart the device-manager from system tray.
    If it doesn't help, then try the following:
    - stop the device manager
    - Remove c:\Docement and Settings\<your User>\javame-sdk folder.
    - Ran the device manager from <SDK>/bin directory
    - try to debug again.
    Did you tried to change port 51307 to another.
    Early access build had some problems with device manager, I hope that final release will be better :)
    BR,
    Igor

  • Persistence of data in J2ME mobile device using RMS

    Hi. Just want to ensure that RMS can let us store some values in the mobile device. I'm using emulator to try this out. Everytime i close the emulator, the data stored in the RecordStore's gone. How about in real mobile device?
    For some reasons, my jad and jar can't be installed in my Nokia 6210. It keeps giving me "Invalid Jar file" error.
    So, my main question is whether RMS really stores the value in the mobile device and can be retrieved everytime that MIDlet app's run again.
    The other question is why is it that my jar can't be installed in my Nokia 6210? I just built it with NetBean with J2ME and it could be run on the emulator perfectly.
    Thanks a lot.

    Hi. For the installation to my phone, i have solved it by changing my app's MIDP version 2.1 to 2.0.
    For the persistence of data part, i changed the Storage->"Storage Root Directory" to "\save" in Preferences of SJWTK and re-run my app on the emulator and my phone. However, it seems that the record store's data is not persisted. So, i assume it has something to do with my code. My code is as below. Can anyone give me some clues on what i have done wrong? Thanks.
    public TheConstructor(MIDlet midlet, Form form, int partnerId){
         try
          // The second parameter indicates that the record store
          // should be created if it does not exist
            rs = RecordStore.openRecordStore(REC_STORE_NAME, true );
            if (rs.getNumRecords() == 0) {
                RecordIdParam = getAdsParam();
                if (clientIdParam.length > 0) {
                    clientId = RecordIdParam;
                    writeRecord(RecordIdParam);
                    readRecords();
                    closeRecStore();  // Close record sto
            else {
                readRecords();
                closeRecStore();  // Close
         catch (Exception e)
          db(e.toString());
    private void db(String str)
        System.err.println("Msg: " + str);
      public void closeRecStore()
        try
          rs.closeRecordStore();
        catch (Exception e)
          db(e.toString());
       public void writeRecord(String str)
        byte[] rec = str.getBytes();
        try
          rs.addRecord(rec, 0, rec.length);
        catch (Exception e)
          db(e.toString());
      public void readRecords()
        try
          // Intentionally make this too small to test code below
          byte[] recData = new byte[5];
          int len;
          System.out.println("num of records is " + rs.getNumRecords());
          for (int i = 1; i <= rs.getNumRecords(); i++)
            if (rs.getRecordSize(i) > recData.length)
              recData = new byte[rs.getRecordSize(i)];
            len = rs.getRecord(i, recData, 0);
            RecordIdParam = recData;
        catch (Exception e)
          db(e.toString());
      }

  • Problem with RecordStore

    Hi all!
    I am building my first cell phone application and starting with J2ME. I "finished" my implementation but my app is not working properly. I dont know if the data is really being saved on the RecordStore or if the data is not being loaded correctly.
    I have 3 classes: Interface, Data and DAOdata. I will put the main parts:
    //My Interface
    public class Interface extends MIDlet implements CommandListener {
    //In this part I save some data to DataBase
    formPagto.setCommandListener (new CommandListener() {
                public void commandAction(Command c, Displayable s) {
                       if(c == salvaDesp){
                            String tmp = txtVal.getString();
                            float val = Float.parseFloat(tmp);
                            DAOdadata dados = new DAOdata();
                            dados.carregaDados(mesAtual());
                            dados.saveData(val, option, mesAtual());
                            novoDisplay(mList);
                       if(c == cBack)
                            novoDisplay(mListSec);
    //Here I load data from RecordStore. The problem, is that only 0 comes out
    mListMes.setCommandListener (new CommandListener() {
                public void commandAction(Command c, Displayable s) {
                  if(c == cResumo){
                       int x = mListMes.getSelectedIndex();
           DAOdata dados = new DAOdata();
           Data VR;
           VR = dados.loadData(x);
       //In this place all I get is 0%. And this is the problem. I should get different values.
           StringItem alim = new StringItem("Food: ", FloatToString(VR.getFood())+"%");
           StringItem vest = new StringItem("Health: ", FloatToString(VR.getHealth())+"%");
            fromVis.append(alim);
           fromVis.append(vest);
         Display.getDisplay(this).setCurrent(fromVis);
                  else if(c == cBack)
                       novoDisplay(mList);
    //My Data class. It´s a bean
    public class Data {
         private float salary;
         private float food,healty,cars, groceries;
    //Setters
    public void setSalary(float val){
              salary = val;
    //Getters
    public float getSalary(){
      return salary;
    //Finally my DAO class
    public class DAOdata {
    private RecordStore rs = null;
    Data dados;
    int month;
    public void loadDataBase(){
              try
                rs = RecordStore.openRecordStore(PERFIL_DB, true);
             catch (Exception  e){
                  System.out.println("Problem loadDataBase()");
    //Load data from RecordStore
    public Data loadData(int month){
              try{
               byte[] data = rs.getRecord(month);
               DataInputStream is = new DataInputStream(new ByteArrayInputStream(data));
               dados.setFood(is.readFloat()); 
               dados.setHealth(is.readFloat());       
               dados.setCars(is.readFloat());
               dados.setGroceries(is.readFloat());
               is.close( );
              }catch(Exception e){
                        //Never get exceptions in here
                   e.printStackTrace();
              return dados;
    //Saving data to RecordStore.
    public void saveData(float val, String tipo, int month){
              if(tipo.equals("Food")){dados.setFood(val);}
              else if(tipo.equals("Health")){dados.setHealth(val);}
              else if(tipo.equals("Cars")){dados.setCars(val);}
              else if(tipo.equals("Groceries")){dados.setGroceries(val);}
              try{
               ByteArrayOutputStream baos = new ByteArrayOutputStream( );
               DataOutputStream os = new DataOutputStream(baos);
               os.writeFloat(dados.getFood());
               os.writeFloat(dados.getHealth());
               os.writeFloat(dados.getCars());
               os.writeFloat(dados.getGroceries());
               os.flush();
               os.close( );
               byte[] data = baos.toByteArray( );
              rs.setRecord(mes, data, 0, data.length); //I use setRecord since the data is already initialized
               rs.closeRecordStore();
              }catch(Exception e){
                        //Never get exceptions in here
                   e.printStackTrace();
    //In this method I populate the RecordStore for the First time. I call this method 12 times, one per month
    public void initRecordStore(int month){
              dados.setFood(0);
              dados.setHealth(0);
              dados.setCars(0);
              dados.setGroceries(0);
              try{
                    ByteArrayOutputStream baos = new ByteArrayOutputStream( );
                    DataOutputStream os = new DataOutputStream(baos);
                    os.writeFloat(dados.getFood());
                    os.writeFloat(dados.getHealth());
                    os.writeFloat(dados.getCars());
                    os.writeFloat(dados.getGroceries());
                    os.close( );
                    byte[] data = baos.toByteArray( );
                   int id = rs.addRecord(data, 0, data.length);
                   rs.closeRecordStore();
                   }catch(Exception e){
                        //Never get exceptions in here
                        e.printStackTrace();
         }So, all that I get are 0% as a result. I dont get any exceptions when I load or save data. I dont know how to solve it. Any help will be welcome.
    Thank you all

    Hi, thanks for your answer.
    Actually I have seen a lot of examples before using the RecordStore.
    Maybe my problem is the way I am using the loadData() to retrieve information to another class. I am trying in a different way.
    Anyway, I will check more examples.
    Thank you =)

  • Chinese character in RecordStore

    Hi all,
    I am new to j2me. is it possible to key in Chinese character and store it in recordstore, and i can display the character back when i view the record?
    i have go through many examples of j2me encoding. but i still don't have any idea about how to do this.
    Thanks a lot...

    HongHong -
    There may be some tips you can use on www.77new.cn/program/i/1173293079453/001/029/14438.html -- I don't know chinese and the translation wasn't good enough for me to be sure about it.
    Have you tried? If your emulator or handset allows you to key in Chinese characters in a textField, they should be available via getString()and the resulting string should get stored OK, of course being a DBCS there wll be 2 bytes per letter.
    Recover the string from the RecordStore using
    new String(recordStore.getRecord(n));I have a MotoROKR E6 with alternative Chinese keyboard, shall experiment and get back to you in a day or two.
    Meanwhile, try for yourself and post the results.
    Regards, Darryl

  • Socket error in j2me

    Hi,
    Here is the scenario:
    I have a servlet application hosted on the Tomcat webserver [ver 3.2.1] on the internet. The client midlet applicaiton is run on the j2me emulators from sun and codewarrior. The entire application works great ..
    Now, a different team uses Acompli 008 over GPRS network (test env) and runs the same midlet client application. Almost evertime I see this error message on my webserver --
    2001-06-21 03:42:53 - ContextManager: SocketException reading request, ignored - java.net.SocketException: Connection
    reset by peer: JVM_recv in socket input stream read
    at java.net.SocketInputStream.socketRead(Native Method)
    at java.net.SocketInputStream.read(SocketInputStream.java:86)
    at java.io.BufferedInputStream.fill(BufferedInputStream.java:186)
    at java.io.BufferedInputStream.read(BufferedInputStream.java:204)
    at org.apache.tomcat.service.http.HttpRequestAdapter.doRead(HttpRequestAdapter.java:115)
    at org.apache.tomcat.core.BufferedServletInputStream.doRead(BufferedServletInputStream.java:106)
    at org.apache.tomcat.core.BufferedServletInputStream.read(BufferedServletInputStream.java:128)
    at javax.servlet.ServletInputStream.readLine(ServletInputStream.java:138)
    at org.apache.tomcat.service.http.HttpRequestAdapter.readNextRequest(HttpRequestAdapter.java:129)
    at org.apache.tomcat.service.http.HttpConnectionHandler.processConnection(HttpConnectionHandler.java:195)
    at org.apache.tomcat.service.TcpWorkerThread.runIt(PoolTcpEndpoint.java:416)
    at org.apache.tomcat.util.ThreadPool$ControlRunnable.run(ThreadPool.java:498)
    at java.lang.Thread.run(Thread.java:484)
    I'm using httpconnection syntax, POST method for data transmission and the data size is approx 1-2K bytes.
    After this error message pops on my webserver screen, the client device freezes ..
    Do anyone have any ideas or suggestions or solutions ??? Is anyone aware of this or encountered this error message ??
    The worst part is that i'm unable to even simulate this using the emulators ..
    Thanks a lot in advance ..
    S.

    Perhaps you could post your code on the forum so that we might be able to help you better?
    Anyway, check also if you are using a get or post request from the midlet cus the Post requests have been known to give a few people problems.

  • How to read a .pdb file using J2ME

    hi all,
    I am using J2ME to write a program that need to read a .pdb file.
    The .pdb file was generated by other application.
    The .pdb file could not be open using J2ME's RecordStore class.
    How can I open the .pdb file using RecordStore or use other approach?

    You'll need the FileConnection api in JSR-75. Note that your device needs to support this! And no, there is no code to read the file format. You'll need to do that yoursels.

  • RecordStore??

    I have a program that works as text entry system, i created it using canvas. It just like the normal typing program (not T9 dictionary), except it store words that is not existed in the RecordStore and use it as a suggestion, the next time user type with the same prefix.Suggestions appear in a box in the center of the canvas. I don't know what is wrong with the program. It runs but doesn't give any word suggestion. Can anyone please check the code for me.?
    Edited by: avaJ on Mar 20, 2008 1:08 PM

    PLEASE IGNORE THE PREVIOUS CANVAS CLASS, I FORGOT TO ADD SOMETHING ON THAT CLASS
    This is the My Canvas Class.. It takes input from users and draw the characters on the screen.
    This class calls some method from RSWord class to do queries, add new data, and update data.
    whenever user typed a letter, the program check whether word that started with that letter existed in RecordStore or not?
    if yes it will retrieve the top 5 words(with the highest frequency of use) and show it in a box,
    users may select the word by pressing the number associated to the order of the word inside the box, frequency of the suggested word that is selected by the user will be incerased by 1 and updated to recordStore.
    if the words with that prefix is not existed, the program will wait until user pressed space, then it will recognized the typed letter as a word and add it to the record store
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    package textEntry;
    import 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
        wordRS db;
        Timer keyTimer;
        textEntryMain main;
        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 timer printed or it is at begining
        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;
        //int previndex=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;
        //Char Selection speed
        private int selection_speed=150;
        //font color (blue)
        private int red=0,green=0,blue=255;
        //Background color (white)
        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
            justPressed=getKeyName(keyCode);
            time=System.currentTimeMillis(); // record the time when the keypress is pressed
            if(justPressed.equalsIgnoreCase("NUM0")){ //caps lock show indicator
                if(zeroPress == 0){
                    currentIndicator="ABC";
                    zeroPress++;
                    keys=capitalKey;
                    drawIndicator(currentIndicator);
                    //set the string buffer to another one
                if(zeroPress == 1){
                    currentIndicator="123";
                    zeroPress++;
                    keys=numbKey;
                    drawIndicator(currentIndicator);
                if(zeroPress == 2){
                    currentIndicator="abc";
                    zeroPress=0;
                    keys=capitalKey;
                    drawIndicator(currentIndicator);
            if(justPressed.equalsIgnoreCase("SEND")){ //send button allocated as clear button
                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==42){//35
                    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{
                index=keyCode-49;
                //ACCEPTING USER KEYPRESS TO SELECT THE SUGGESTED WORD --START
                if(sBoxAppeared && index<=4){ 
                    drawSelectedSuggestion(index);
                    db.updateFrequency(index);
                    sBoxAppeared=false;
                    word = new StringBuffer();
                 //ACCEPTING USER KEYPRESS TO SELECT THE SUGGESTED WORD --STOP
                else{
                    int limit = 0;
                    keypress=true;
                    if(index==0){limit=34;}
                    if(index==1 || index==2 || index == 3 || index == 4
                    || index ==5 || index==7){ limit=3;}
                    if(index==6 || index==8){ limit=4;}
                    if(keyCode == prevPressed || dontPrint){ //dontPrint: timer excecuted confirmpaint so counterPress has to be reseted
                       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 void closeDB() throws RecordStoreException
        {db.closeRS();}//this method destroy the enumeration and close the database
             /*   THIS IS FOR NUMB if(currentIndicator.equals("123")){
                    MyCanvas.ch=keys[index].charAt(0);
                    ConfirmPaint(ch);
                else{
    //task class for schedule on constructor

  • How to Deploy J2ME applications with data in RMS?

    Hello everyone,
    I am designing a J2ME application, a simple "Who wants to be a millionaire game". It stores questions and answers from a rms datastore. I want to to how can I deploy this application with questions and answers in the recordstore. Each time I run the emulator, the data stored previously gets deleted. Is it possible to attach the rms recordstore along with the .jar or .jad files? If so how can I do it. Please help.
    Thank you all in advance.

    Thank you Sypress.. When I install it the code works fine. But I wanted to include data with the application. I think I found a way way. I added the data in a text file and while starting the application I inserted data from the file into the recordstore.

  • Randomizing recordStore

    hi,
    im having this peculiar problem.
    Aim: Extracting a record randomly from a RecordStore with every record gaving almost equal probability of being returned.
            try
                numRecs = myDatabase.getNumRecords();
            catch (RecordStoreException rse)
                 System.out.println(rse);
                 rse.printStackTrace();
            System.out.println("There are " + numRecs + " records in the record store");
            if(numRecs != 0)
                try
                    int someNumber = (int) rand.nextInt() % numRecs;
                    recordToBeReturned = new String(myDatabase.getRecord(someNumber));
                catch(RecordStoreNotOpenException rsnoe)
                    System.out.println("The record store is not open");
                    rsnoe.printStackTrace();
                catch(InvalidRecordIDException irie)
                    System.out.println("The Record ID is invalid");
                    irie.printStackTrace();
                catch (RecordStoreException rse)
                     System.out.println("There has been a general exception");
                     rse.printStackTrace();
    Problem: the "getRecord()" method throws up an Arithmetic Exception. i even tried using the variant of getRecord(int, byte[],int). still no use.
    So, could anyone suggest a way to randomize using RecordComparator so that i can retrieve random records with enumerate().
    thanx in advance.
    =====
    kiran

    hey guyz,
    i finally hit upon a solution which seems rather crude.
    but im not sure whether the probablity for each record is almost equal...please help me analyze this..here is the code fragment:
    public class Database implements RecordComparator{
    public synchronized RecordEnumeration enumerate() throws RecordStoreNotOpenException
           return myDatabase.enumerateRecords(null, this, true);
        public Record getARecord()
            Record recordToBeReturned = new Record();
            int numRecs = 0;
            int someID = 0;
             /* class Record is defined as follows:
               *  class Record
               *         String actualRecord;
               *        int  recordID;
            try
                RecordEnumeration rEnum = this.enumerate();
                if(rEnum.hasNextElement() == false)
                    rEnum.reset();
                recordToBeReturned.actualRecord = new String(rEnum.nextRecord());
                recordToBeReturned.recordId = rEnum.nextRecordId();
           //CATCH EXCEPTIONS HERE
           *generate a random number between -1 and 1.
           * so this method will randomly oscillate between
           * EQUIVALENT, PRECEDES AND FOLLOWS
        public int compare(byte [] rec1, byte [] rec2)
            Random rand = new Random();
            int randomNumber = (int) rand.nextInt() % 3;
            return randomNumber - 1;
    }

  • Chat between j2me clients and using a Servlet server

    Java gurus, please help me..
    I'm wondering if I could set up a sort of chat functionality between two j2me clients. I wish to use Java servlets as my server and Tomcat to deploy it. Is this possible? Can i do these by using http connection only or do i have to use sockets? If i use sockets, how will i configure Tomcat, or do i still need Tomcat?
    Hope someone could help! Thanks in advance! =)

    Basically it means you should have a Thread that loops and make an http request every x seconds. Before sending the request it should check if the user has typed anything, and send that with the request. The server should keep track of all the chat messages sent, and forward to all the other clients when they request an update. To keep track of what clients have received what messages, you could have a time stamp for each message, and a "last update" field for each client.
    The client should run something like this in a thread:
    while (iAmRunning) {
      url = "......." // address of your server
      if (the user typed anything since the last time we sent a request) {
        url = url + "?msg=" + whatTheUserTyped; // maybe another parameter for private messages?
        reset what the user typed (so it won't be sent next time);
      send the request;
      get the response containing what the rest of the users have
        typed since my last update;
      update the display with the latest messages;
    }And the server would handle a request like:
    if (the request contains a message) {
      save the message with the current time;
    check when was the previous update for this user;
    get all messages where the timestamp is later than the last update;
    set the last update field for the user with to the current time;
    respond with all the messages;

Maybe you are looking for

  • Unable to start service 'com.sap.aii.adapter.jms.svc'

    Hi people, After I have successfully deployed the external drivers jdbc/jms drivers on a PI 7.1 system trough JSPM using the com.sap.aii.adapter.lib.sda file but now the com.sap.aii.adapter.jms.svc and the com.sap.aii.adapter.jdbc.svc do not want to

  • Female Mini port to VGA adaptor?

    Hey Everyone I am looking for female Mini port to VGA adaptor, and i wondered if anyone knew if something like this was made? Thanks for any help or suggestions

  • Transaction Variant for SHD0 in CAT2

    Hi,    We have a requirement to default the wage type in CAT2 screen. Is it possible to accomplish this using the SHD0 transaction variant.  The wage type appears in the table control in the CAT2 screen .Kindly advice. Regards, Prabaharan.G

  • Put the Button Script in the Actions Frame

    When I click each button I want it to advance the play head to the Frame Lable. This code works but I need to change the state of the button. If I change the button State to Graphic in the Key Frame Lable it makes the code not work. I would like to h

  • BAPI_InspectionPlan_Create-Create Operation based on First Operation

    Hi All, I am uploading inspection Plan using BAPI_Inspectionplan_create method.For This one operation had already been created.I need to create the next operations as a copy of first operation except for the change in operation description. Could som