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

Similar Messages

  • Mp3 and RecordStore Capable Emulator

    Currently I'm trying to develop an application that plays back mp3's. I am just wondering if there exists an emulator that can handle both, record sets and mp3 playback.
    WTK22 does a good job of handling recorcStores, but can not handle Mp3 playback.
    I did find a motorola emulator that handled mp3 playback, unfortunately it crashes as soon as I try and load information into the recordStore.
    If anyone knows of one, perhaps they could pass along the name, or even a link.
    Another question I do have about WTK22 is, is there any way of increasing the recordStore size, or is it stuck at 1MB . . . and what is the average size of a record store on a new phone these days?

    I wasn't sure what is RecordStore but apparently it is MIDP's way of persisting data.
    As it shows, I have little knowledge of JavaME, so I don't know if that's a problem with the emulator or the usage of RecordStore within JavaFX or something else.
    Now, perhaps you can use the [javafx.io.Storage|http://java.sun.com/javafx/1.2/docs/api/javafx.io/javafx.io.Storage.html] class for persisting data, it is designed to work both in JavaME and on desktop.
    It might offer less features than RecordStore, though.

  • About workin with RecordStore

    i have been workin on an application for Palm OS which deals with a lot of database.the application is workin fine and the data also seems to be consistent. however the problem started when i started to work with conduit for tha application. can someone tell me about a better way to manipulate the data stored by the recordstore using java conduit.
    thank u !

    kAWT is built on top of kJava and only works with kJava (I am not sure if anyone has ported it to MIDP). kAWT has nothing to do with databases, it is only for GUI management similar to J2SE AWT. So if you want to use kJava, you can use kAWT for your GUI, but you do not have to. Also, if you use kJava, regaurdless of kAWT, you can use the Palm database - the two are not mutually exclusive.
    Now for MIDP. kAWT, as far as I know, has not been ported to MIDP. MIDP is a replacement for kJava, and it also runs on Cell phones. MIDP is somewhat OK for Palm, but really does not take full advantage of the Palm and the palm native GUI components. On this forum, there is better support for support for MIDP than kJava.
    If you are going to write an application for the Palm and only for the Palm, and it must be in Java, AND you need to take advantage of sophisticated Palm OS features, consider downloading and using IBM's J9 compiler (VAME). It opens up the full Palm OS. However, writing Palm applications is not as easy as MIDP or kJava, and will take longer to learn. The support for J9 is through the IBM VAME newsgroup.
    If your application is simple, and you do not need to use the IR port, serial port, access other databases other than your own, or need to have tight control over the user interface, go with MIDP. Download Forte and the wireless toolkit from Sun and follow the install directions, and read the PDF documents in the /doc directory.
    Also, there are a large number of postings in this forum about using MIDP on Palms and MIDP with the wireless toolkit and Forte. There are also people form Sun who monitor and reply to problems in this forum when they pertain to MIDP. kJava does not have this level of support.
    Once you have picked your development tools, and if you have further problems, lets resolve them one at a time. Post the actual error message as a new topic and people in the forum will take it from there.
    Don

  • 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

  • Recordstore backup

    Hi,
    I want to backup my recordstore data on my PC using the P900 with CLDC 1.0, MIDP 2.0
    So far the only possibilities I see is:
    - Backup the phone
    - make a http connection and backup on the remote server
    - make a bluetooth connection to my PC
    Are there any other, "simple" possibilites?
    Can I not simply copy the recordstore files from my mobile phone to my PC (where are they stored)?
    Thanks for your help
    Bernhard

    Hi together,
    thanks a lot for your answers, with your help I managed to do the backup.
    I use FileMan http://www.symbianware.com/product.php?id=fileman_p800&pl=se_p900 and just have to copy these two files:
    \system\MIDIlets\RMSProtectionFile
    \system\MIDIlets\<strange number>\rms.db
    I tested the backup and it was working fine!
    Cheers
    Bernhard

  • Reading the contactlist without PIM ,RecordStore and APDU

    Hi,
    I was playing with a commercial midlet and i discovered something strange.
    The midlet does not import the contact list using PIM ,the recordstore functions or the APDU protocol!
    How is that possible?
    I tried for example to use the RecordStore.listRecordStores() but of course I can't see the SIM contact list.
    Hence the window that allow the user to choose from the contact list has an icon which is not present in the icon directory of the jar and nor in the resource bin.
    Is it calling a special funciont that enable a window to select the contacts?
    Anybody can help me to understand this trick?
    The midlet is configured as:
    MIDP 1.0 and CLDC 1.0
    The package imported are:
    lcdui and recordstore

    I found that the JSR 185 specification allow this functionality but only for MIDP 2.0.
    Reading the documentation:
    Devices usually have a contact list, a place where the user may enter the names and phone numbers of people they know. To simplify building text messaging applications, JSR 185 requires that this phone book be available to populate TextField or TextBox components.
    But where can I find an example on how to use that fantastic component?

  • Problem with RecordStore.deleteRecordStore

    since rms doesnt have a recordstorerename function i have to copy all records to a new recordstore and delete the old one.
    the problem is that i need to close the from recordstore twice or i get a
    recordstore is still open exception.
    anyway to fix this ?
    RecordStore from = RecordStore.openRecordStore("thestore", false);
    RecordStore to = RecordStore.openRecordStore(tb.getString(), true);
    for (int i=1;i<=from.getNumRecords();i++) {
    byte[] data = from.getRecord(i);
    to.addRecord(data,0,data.length);
    to.closeRecordStore();
    from.closeRecordStore();
    from.closeRecordStore();
    RecordStore.deleteRecordStore("thestore");

    Hello,
    I checked this with WTK 2.2, but as expected I got the Exception RecordStoreNotOpenException, if I try closing the record store twice times.
    I think you just opened the record store once before and forgot to close it. MIDP2 says: 'MIDlet needs to make a balanced number of close calls as open calls before the record store is closed. ' And this applies to one RecordStore only.
    So have a look at your code and check this.

  • Problem in RecordStore

    As we know that we have a method deleteRecord(int recordId) in RecordStore Class. it deletes the record ID associated with the record.
    So, when we delete a record, it deletes the record along with the recordID but does not rearrange the remaining records in the recordstore. we have to do it manually. i am using a logic to set the new recordID for the remaining records but it is not working well. So if you know how to solve this problem, please tell me....

    You cannot get the complete RDBMS kind of functionality incorporated in Java ME client since it is only a tiny foot-print provided to store bytes of information.
    Regarding your problem the record ID is treated as an primary key and once deleted cannot be retrieved back. Better to use setRecord() call instead.
    ~Mohan

  • Desperation: RecordStore.deleteRecord() freezes on Nokia6230

    Hi,
    I've yet another problem with Nokia 6230 RecordStore system.
    In loop I call RecordStore.deleteRecord(recordID) and when it gets to some record, MIDlet freezes. The only thing I can do then is stop execution of the whole MIDlet.
    Why does that happen ?
    It happens with some records, but it doesn't with others. I don't see anything particular on records, on which it freezes.
    Plese help. RMS on Nokia phones is driving me mad. I'm supprised that Nokia (which I otherwise regarded as professional company) produced such sh*te implementation.
    Michal

    The record store has 32272 bytes. I put it on http://sankotm.freeshell.org/p36.rms, so it should be possible to test it at your machine, if you wanted to do it.
    I print out any exceptions that are thrown, but there is none thrown before it gets to record 4, where it freezes. I can't prove it's frozen (and not just taking very long time), but I waited for 30 minutes and it didn't get anywhere, so I can assume it is frozen.
    Michal

  • 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;
    }

  • Delete existing RecordStore and then open a newer one with same name

    Hey All,
    I'm working in J2Me for Nokia S40 DP2.0 SDK 1.0.
    I want to delete my existing RecordStore (i. e; Products) and then open a new RecordStore as same name(Products) But
    There is an Exception thrown that RecordStore is Open;
    my deletion process is given below :
    public void deleteRecStore(String recordName) {
    if (RecordStore.listRecordStores() != null) {
    try {        
    RecordStore.deleteRecordStore(recordName);
    } catch (Exception e) {
    e.printStackTrace();
    public void createRecStore(String recordName, Vector data, int insertType) {
    if(recordName.equals("") && (recordName != null)) {
    try {
    if(insertType == this.NEW_REC) {
    rs = RecordStore.openRecordStore(recordName,true);
    this.closeRecStore();
    this.deleteRecStore(recordName);
    rs = RecordStore.openRecordStore(recordName,true);
    Can anybody pls help me...
    why I can't open a new recordstore like this ??
    If there any process then what is that ???
    Rania...

    This question belongs in the [CLDC and MIDP forum|http://forums.sun.com/forum.jspa?forumID=76]. I'll move it there in an hour or so.
    I would suggest that in addition to printing the stack trace of any Exception, you could append the Exception.toString() to a Form (or display it in an Alert) to see whether any exceptions are being thrown.
    db

  • Cant delete a recordstore

    Hi,
    I was wondering if their is anybody that can tell me why a record store that I have created cannot be deleted using the "RecordStore.deleteRecordStore( );" method.
    I have written a bit of code which when executed should delete the entire record store "PLAYERSTORE", but for some reason it does not.
    My code:
    public void deleteRecordStore()
              try
                   System.out.println("Store deleted");
                   RecordStore.deleteRecordStore( "PLAYERSTORE" );
              catch( RecordStoreNotFoundException e )
                   System.out.println("Exception: "+e);
              catch( RecordStoreException e )
                   System.out.println("Exception: "+e);
    At first i thought it might be because i hadnt closed the record store after using it in previous methods, unfortunatelly this was not the case.
    Please help

    Still no joy with deleting the record
    I think this is what you are looking for (StackTrace)...
    java.lang.NullPointerException
         at CourseListing.deleteRecord(+35)
         at CourseListing.commandAction(+49)
         at javax.microedition.lcdui.Display$DisplayAccessor.commandAction(+282)
         at javax.microedition.lcdui.Display$DisplayManagerImpl.commandAction(+10)
         at com.sun.midp.lcdui.DefaultEventHandler.commandEvent(+68)
         at com.sun.midp.lcdui.AutomatedEventHandler.commandEvent(+47)
         at com.sun.midp.lcdui.DefaultEventHandler$QueuedEventHandler.run(+250)
    This is what is displayed when I try and delete a record
    I have posted the whole code listing bellow the "bold" code is the code that deletes a record
    import javax.microedition.midlet.MIDlet;
    import javax.microedition.lcdui.*;
    import java.util.*;
    import javax.microedition.rms.*;
    public class CourseListing extends List implements CommandListener
         private RecordStore rs;
         private GSAP midlet;
         private Command backCommand = new Command("Back", Command.BACK, 0);
         private Command deleteCommand = new Command("Delete", Command.SCREEN, 1);
         private Command viewCommand = new Command("View", Command.SCREEN, 1);
         private Ticker courseListing = new Ticker("The following is a list of courses stored by the GSAP. You have the option of, viewing course details, editing course details, or deleting a course entirely.");
         public CourseListing(GSAP midlet)
              super("COURSES", Choice.EXCLUSIVE);
              this.midlet = midlet;
              addCommand(backCommand);
              addCommand(deleteCommand);
              addCommand(viewCommand);
              setTicker(courseListing);
              setCommandListener(this);
              readRecords();
         public void readRecords()
              //Open COURSESTORE record store
              RecordStore rs = null;
              try
                   rs = RecordStore.openRecordStore("COURSESTORE", true);
                   System.out.println("COURSESTORE open");
              catch(RecordStoreNotFoundException rsnfe)
                   System.out.println("The record store you are trying to open does not exist :"+rsnfe);
              catch(RecordStoreFullException fsfe)
                   System.out.println("The record store cannot store anymore data :"+fsfe);
              catch(RecordStoreException rse)
                   System.out.println("An error has occured when using the record store :"+rse);
              //Read records from the PLAYERSTORE and store in an array
              try
                   byte[] recData = new byte[5];
                   int records;
                   System.out.println("At the for loop");
                   for (int i = 1; i <= rs.getNumRecords(); i++)
                        System.out.println("Inside for loop");
                        // Allocate more storage if necessary
                        if (rs.getRecordSize(i) > recData.length)
                        recData = new byte[rs.getRecordSize(i)];
                        records = rs.getRecord(i, recData, 0);
                        //System.out.println(rs.getRecord(i, recData, 0));
                        System.out.println("Record ID#" + i + ": " + new String(recData, 0, records));
                        //append("Record ID#" + i + ": " + new String(recData, 0, records), null);
                        append(""+ new String(recData, 0, records), null);     
              catch (Exception e)
                   System.err.println(e.toString());
              //Close the record store
              try
                   rs.closeRecordStore();
              catch( RecordStoreNotOpenException e )
                   System.out.println("Record store already closed!");
              catch( RecordStoreException e )
                   System.out.println("Exception:"+e);
         public void commandAction(Command c, Displayable d)
              if(c == backCommand)
                   midlet.courseMenuScreenShow();
              else if(c == viewCommand)
                   System.out.println("View the selected course details");
              else if(c == deleteCommand)
                   deleteRecord();
                   System.out.println("The selected course will be deleted");
              else
                   processMenu();
         private void processMenu()
              try
                   List down = (List)midlet.display.getCurrent();
                   switch(down.getSelectedIndex())
                        case 0: midlet.addCourseScreenShow();
                        case 1: System.out.println("Manage courses");
              catch(Exception ex)
                   System.out.println("processMenu::"+ex);
         public void deleteRecord()
              try
                   int id = 1;
                   System.out.println("WE ARE HERE NOW");
                   rs.openRecordStore( "PLAYERSTORE", true );
                   System.out.println("WE ARE HERE NOW FOR GOODNESS SAKE");
                   rs.deleteRecord(id);
                   System.out.println("WE ARE HERE NOW FOR GOODNESS SAKE OHHH YEAH");
              catch(RecordStoreNotOpenException e)
                   System.out.println("Exception: "+e);
              catch(InvalidRecordIDException e)
                   System.out.println("Exception: "+e);
              catch( RecordStoreException e )
                   System.out.println("Exception:"+e);
                   e.printStackTrace();
              //Close the record store
              try
                   rs.closeRecordStore();
              catch( RecordStoreNotOpenException e )
                   System.out.println("Record store already closed!");
              catch( RecordStoreException e )
                   System.out.println("Exception:"+e);
         }//End of deleteRecord() method     
    }

  • RecordStore bytearray length not long enough!

    Can anyone tell me why the following code returns this error message... java.io.EOFException
    Something to do with the byte array no being big enough but how is this possible when I'm first looping through the RecordStore and getting the largest size, then initializing the byte array (which will hold what comes from getRecord()) with that size.
    try {
            int SizeOfRecord = 0;
         for (int x = 1; x <= rs.getNumRecords(); x++) {
              if (rs.getRecordSize(x) > SizeOfRecord)
                    SizeOfRecord = rs.getRecordSize(x);
         byte[] recData = new byte[SizeOfRecord];
         ByteArrayInputStream strmBytes = new ByteArrayInputStream(recData);
         DataInputStream strmDataType = new DataInputStream(strmBytes);
         for (int i = 1; i <= rs.getNumRecords(); i++) {
              rs.getRecord(i, recData, 0);
              System.out.println(strmDataType.readUTF());
                 strmBytes.reset();
         strmBytes.close();
         strmDataType.close();
         } catch (Exception e) {
               System.out.println(e.toString());
         }Any help would be great, thanks

    Thanks for the reply.
    In response the reset() method is supported, it's listed in the api docs for midp.
    Let me re-state what I want to happen...
    In order to read records from RecordStores you must initialise a ByteArrayInputStream and a DataInputStream.
    When initialising a ByteArrayInputStream you must pass a byte array, but this byte array must be initialised itself, meaning that I must specify it's size before I've even started looping through records.
    Fair enough so far, so I loop through the RecordStore using a standard for loop and use the getRecordSize() method to compare the current record's size to the previous one. If the current record's size is bigger than the previous one then overwrite a variable to hold the biggest size.
    When the code is run the biggest record size is apparently 153 bytes, which generates an EOFException. When I hard code the size of the byte array to 3500, it works - why such a big difference?
    can anyone tell me if there is a serious logic flaw here or whether there is another way of doing such a thing.
    Thanks for your time
    poncenby

  • Weird RecordStore error - help...anybody?

    I am receiving an error from a command of the following form:
    setRecord(1, data, 0, data.length)
    where data is a byte array (defined by a toByteArray() from a ByteArrayOutputStream).
    The error states:
    javax:microedition.rms.RecordStoreException: Error setting record data: java.io.IOException: write exceeds maximum file size.
    The thing I find weird is that, when I display the getSize() and getSizeAvailable() on the RecordStore, I get really big numbers, like:
    size is 62200
    size available is 546972
    while my data is small,
    data.length = 9536
    So I am confused by the "exceeds maximum file size" notice. The data is definitely small enough to fit in what memory I have available. And...Is there a file involved or is something not quite right with the message, which also appears to have the form of two error messages merged as one.
    Does anyone have any ideas as to what I am encountering here? Would anyone know of anyway I can track down such a problem? I'm a bit lost as to how to debug this since it seems like there isn't much I can play around with given the somewhat limited amount of things I can do (and mess up) with RecordStores. Could it be a memory leak/overwrite? (I'm not sure that that is too likely, particularly in Java, but I'm at a bit of a loss as to where to find problems to try to get my hands on.)
    Thanks for any help, advice or thoughts!

    Hi, I'm writing app, which saves images to RS.
    public void saveImage(String path) {
            RecordStore rs = null;    // Record store
            String RECORD_STORE = path; // Name of record store
            addImageName(path);
            try {
                rs = RecordStore.openRecordStore(RECORD_STORE, true );
                rs.addRecord(data, 0, data.length);
                System.out.println("data lenght : " + data.length);
                System.out.println("writing finished");
                rs.closeRecordStore();
            catch (Exception e) {
            dpy.setCurrent(l);
        }this works...this methos saved even 25kB...

Maybe you are looking for

  • Issue with photos in iMovie - looks normal in timeline but won't play

    I'm having an issue with importing photos into iMovie. I've done it many a time without trouble but suddenly, when I really need it...ahh! The problem is with a video I've already exported once-I'm not sure if that's related. I created a slide in Pow

  • How can I customize Waveform Chart?

    I want a routine to display selected waveforms on a chart. The input is a waveform array.  The chart should have the following: 1. Y axis labels using the waveform names 2. Legend plot labels using the waveform names 3. X axis in seconds from the sta

  • Query on Reoprts-pl/sql function body returning sql query

    Hi, I am facing a starnge problem.. and would like to know the reason for it. The situation is as follows: I have a report (pl/sql function body returning sql query based). My query is as follows: declare l_query1 varchar2(2000); begin if (:P102_min_

  • Apple TV3 optical connection to Denon AVR-1705 fails.

    Are these two compatible at all? Has anyone ever set them up successfully? The optical cable from ATV3 is connected to the Opt2 input on the Denon. The Opt2 input is properly assigned to "TV" mode and the input mode is automatic. The system does seem

  • RE: Multiple Selection - there is a way

    Hi, There is a way to provide multiple selection (Highlighting) of rows in Array widget. No need to provide toggle field etc. to show selection of a row. You can exactly do what you want in ArrayField widget i.e. using Shift-click and ctrl-click key.