RecordStore, how to?

I'm having trouble saving settings and stuff for my program. I tried using the class that Jimm (ICQ client) uses until I've learned more. It seems really nice, also works great, except that values aren't saved (or loaded!) sometimes.
I have no idea what might be wrong and there's TONS of code so posting won't be a good idea right now, I'm afraid.
Therefore, does anyone have a nice guide or anything on how to use recordstore? I'd like it to work like the windows registry, for instance, in other words, every entry has a name and a value. Recordstores doesn't appear to work like that, or do they?

Yup, that did help some, thanks.
However, I can't get my new code to work properly, and actually I can't figure out if the error is in load(), save() or both...
Anyway, it doesn't save/load properly.
If I try to store the int 1, the int 2, and the string "3" in that order, the result will come out 1, 1, and <empty string> when I load it later on.
"Some" code, I'd be very thankful for some helpful ideas.
import javax.microedition.lcdui.*;
import java.io.*;
import javax.microedition.io.*;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreException;
public class Options implements CommandListener
     public static String sCurrencyList[] = {"Euro, EUR", "USA, USD", "Great Britain, GBP", "Schweiz, CHF", "Denmark, DKK", "Norway, NOK", "Iceland, ISK", "Japan, JPY", "Canada, CAD", "Australia, AUD", "Cyprus, CYP", "Hong kong, HKD", "New Zeeland, NZD", "Singapore, SGD", "S. Africa, ZAR", "Thailand, THB", "Czech Rep., CZK", "Sweden, SEK"};
     public Form optionsForm;
     private Command saveCommand, backCommand;
     private TextField tExchangeRate;
     private ChoiceGroup cgMyCurrency;
     private ChoiceGroup cgForeignCurrency;
     public int MY_CURRENCY = 0;
     public int FOREIGN_CURRENCY = 1;
     public String EXCHANGERATE;
     // Constructor
     public Options()
          try
               RecordStore rs = RecordStore.openRecordStore("opt", true);
               if (rs.getNextRecordID() == 1)
                    System.out.println("DB not found, setting up...");
                    rs.addRecord(null,0,0); // ID 1 = my currency (int)
                    rs.addRecord(null,0,0); // ID 2 = foreign currency (int)
                    rs.addRecord(null,0,0); // ID 3 = exchange rate (string)
                    byte[] buf;
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    DataOutputStream dos = new DataOutputStream(baos);
                    dos.writeInt(17);
                    buf = baos.toByteArray();
                    rs.setRecord(1, buf, 0, buf.length);
                    dos.writeInt(1);
                    buf = baos.toByteArray();
                    rs.setRecord(2, buf, 0, buf.length);
                    dos.writeUTF("7.35");
                    buf = baos.toByteArray();
                    rs.setRecord(3, buf, 0, buf.length);
                    // Set default options, now that the record store has been created
                    this.MY_CURRENCY = 17;
                    this.FOREIGN_CURRENCY = 1;
                    this.EXCHANGERATE = "7.35";
               else // Database already existed, read the info
                    System.out.println("DB found, reading info");
                    byte [] buf;
                    ByteArrayInputStream bas;
                    DataInputStream dis;
                    buf = rs.getRecord(1);
                    bas = new ByteArrayInputStream(buf);
                    dis = new DataInputStream(bas);
                    this.MY_CURRENCY = dis.readInt();
                    System.out.println ("Read MY_CURRENCY: " + this.MY_CURRENCY);
                    buf = rs.getRecord(2);
                    bas = new ByteArrayInputStream(buf);
                    dis = new DataInputStream(bas);
                    this.FOREIGN_CURRENCY = dis.readInt();
                    System.out.println ("Read FOREIGN_CURRENCY: " + this.FOREIGN_CURRENCY);
                    buf = rs.getRecord(3);
                    bas = new ByteArrayInputStream(buf);
                    dis = new DataInputStream(bas);
                    this.EXCHANGERATE = dis.readUTF();
                    System.out.println ("Read EXCHANGERATE: " + this.EXCHANGERATE);
               rs.closeRecordStore();
          catch (Exception e)
               System.out.println("An Exception occurred while reading/creating the DB." + e.toString());
               // Ignore, for now...
     public void show()
          System.out.println("show() invoked");
          saveCommand = new Command("Save", Command.SCREEN, 1);
          backCommand = new Command("Back", Command.BACK, 1);
          optionsForm = new Form("Options");
          Image[] imageArray = null;
          cgMyCurrency = new ChoiceGroup("My currency", Choice.POPUP, sCurrencyList, imageArray);
          cgForeignCurrency = new ChoiceGroup("Foreign currency", Choice.POPUP, sCurrencyList, imageArray);
          tExchangeRate = new TextField("Exchange rate", "", 15, TextField.DECIMAL);
          cgMyCurrency.setSelectedIndex(this.MY_CURRENCY, true);
          cgForeignCurrency.setSelectedIndex(this.FOREIGN_CURRENCY, true);
          tExchangeRate.setString(this.EXCHANGERATE);          
          optionsForm.append(cgMyCurrency);
          optionsForm.append(cgForeignCurrency);
          optionsForm.append(tExchangeRate);
          optionsForm.addCommand(backCommand);
          optionsForm.addCommand(saveCommand);
          optionsForm.setCommandListener(this);
          OptMain.display.setCurrent(optionsForm);
     public void save()
          System.out.println("save() invoked");
          try
               this.MY_CURRENCY = cgMyCurrency.getSelectedIndex();
               this.FOREIGN_CURRENCY = cgForeignCurrency.getSelectedIndex();
               this.EXCHANGERATE = tExchangeRate.getString();
               RecordStore rs = RecordStore.openRecordStore("opt", false);
               byte [] buf;
               ByteArrayOutputStream bas;
               DataOutputStream dos;
               bas = new ByteArrayOutputStream();
               dos = new DataOutputStream(bas);
               dos.writeInt(this.MY_CURRENCY);
               buf = bas.toByteArray();
               rs.setRecord(1, buf, 0, buf.length);
               System.out.println ("Wrote MY_CURRENCY: " + this.MY_CURRENCY);
               dos.writeInt(this.FOREIGN_CURRENCY);
               buf = bas.toByteArray();
               rs.setRecord(2, buf, 0, buf.length);
               System.out.println ("Wrote FOREIGN_CURRENCY: " + this.FOREIGN_CURRENCY);
               dos.writeUTF(this.EXCHANGERATE);
               buf = bas.toByteArray();
               rs.setRecord(3, buf, 0, buf.length);
               System.out.println ("Wrote EXCHANGERATE: " + this.EXCHANGERATE);
               rs.closeRecordStore();
          catch (Exception e)
               System.out.println("An Exception occured in save(): " + e.toString());
     public void commandAction (Command c, Displayable d)
          if (c == saveCommand)
               System.out.println("Received saveCommand");
               this.save();
               OptMain.display.setCurrent(OptMain.mainMenu);
          else if (c == backCommand)
               System.out.println("Received backCommand");
               OptMain.display.setCurrent(OptMain.mainMenu);
}I'm guessing there's a better/easier/prettier way to read and write data, no?

Similar Messages

  • How many recordstore connections can be kept open

    Hi all,
    i have created a J2ME midp2.0 based application,
    it requires to do database operations, for performance i want to keep recordstore open for frequently used record stores.( The open() close() on recordstore are expensive operations on some of the devices).
    how safe is this, is there any threshold on number of recordstore i can keep open.
    please advise
    Thanks

    I would guess 2 billion (2^31-1.) That is because it probably has to keep track of something in java and that suggests an array. And that is the maximum size for an array.
    Of course the actual number is going to be much less than that because it depends on the memory, cpu's, jdbc driver, database and licensing of the database. And probably other OS specific things like thread limits, file limits, resource limits, etc.

  • How does recordstore _actually_ work on a device?

    Hi,
    one of the users of my app is very convinced that my application is at fault for his phones firmware getting messed up. Since j2me is very restricted I find it unlikely that such thing could even happen, especially since only data storing app does is done in recordstore, no fileconnection api is used. However this lead me to ponder how exactly does the recordstore work on device and whether it is possible for it to be somehow responsible for this.
    I think it works by j2me calling some platform API that would do all the reading/writing related to recordstore instead of j2me itself doing the writing. I'd like to hear confirmation about workings of recordstore and any thoughts you might offer concerning possibility of j2me app damaging phone.
    Thanks.

    my question is still standing, does the
    java-virtualmachine directly write recordstore data
    to phone or does it call some phones OS's API to do
    that.
    "...Each record store can be visualized as a collection of records, which will remain persistent across multiple invocations of the MIDlet. The device platform is responsible for making its best effort to maintain the integrity of the MIDlet's record stores throughout the normal use of the platform, including reboots, battery changes, etc.
    A record store is created in platform-dependent locations, like nonvolatile device memory, which are not directly exposed to the MIDlets. The RMS classes call into the platform-specific native code that uses the standard OS data manager functions to perform the actual database operations.
    Record store implementations ensure that all individual record store operations are atomic, synchronous, and serialized, so no corruption of data will occur with multiple accesses. The record store is timestamped to denote the last time it was modified. The record store also maintains a version, which is an integer that is incremented for each operation that modifies the contents of the record store. Versions and timestamps are useful for synchronization purposes..."
    from http://www-128.ibm.com/developerworks/wireless/library/wi-rms/ , a link found
    http://www-128.ibm.com/developerworks/library/j-j2me3/ , at the end of the page...
    is it what you want ????

  • How to pre-populate a RecordStore ?

    Is there a way to pre-populate a RecordStore so that it contains data needed for an application to run right after being installed ?

    Is there a way to pre-populate a RecordStore
    so that it contains data needed for an application to
    run right after being installed ?No, you can't prepopulate a record store. You have to programmatically create and fill all record stores for your MIDlet suite.

  • Urgent help needed: how to display a list of records on the screen

    Hello,
    This is very urgent. Can anyone help me. I have posted this query of mine before also but still no reply came. My whole application is dependent on this problem. Actually I am developing an application for mobile phone using MIDP. I have a record store which contains personal details for users. I am able to add records to the record store. Now I want that these records can be edited. For this I want to display a list of firstname field on the screen (and not console) so that i can select a user to edit its details. I have written the code to read the records and individual fields and display it on the console but i want to display that list on screen. I tried list and array but it s giving some error.
    I am giving the code to read the records below. Please tell me how can I display it in a list on the screen.
    public void readStream(){
    try
    byte[] recData=new byte[50];
    String varname;
    ByteArrayInputStream strmBytes = new ByteArrayInputStream(recData);
    DataInputStream strmData=new DataInputStream(strmBytes);
    if (rsperdt.getNumRecords() > 0){
    ComparatorString comp=new ComparatorString();
    int i=1;
    RecordEnumeration re=rsperdt.enumerateRecords(null, comp, false);
    while(re.hasNextElement()){
    rsperdt.getRecord(re.nextRecordId(), recData,0);
    System.out.println("Record #" + i );
    varname = strmData.readUTF();
    System.out.println("Name #"+varname);
    System.out.println("---------------------------");
    i=i+1;
    strmBytes.reset();
    comp.compareStringClose();
    re.destroy();
    strmBytes.close();
    catch(Exception e){
    System.err.println("read Records class:read");
    }

    I could not understand ur point "post the code in tags". I am pasting the code below. Please help as my whole application is stuck due to this problem and I have a deadline of 7th oct.
    This midlet is getting called from some other midlet.
    import javax.microedition.lcdui.*;
    import javax.microedition.midlet.*;
    import javax.microedition.rms.*;
    import java.io.*;
    import java.util.*;
    public class frmread extends Form implements CommandListener
    static final String rec_store="db_per";
    private RecordStore rsperdt=null;
    private Vector vecname;
    private ChoiceGroup chname;
    private boolean flagSortByPriority = false, flagShowPriority = true;
    private Form fmmain;
    private Command cmdBack;
    private teledoc midlet;
    public frmread(String title, teledoc midlet)
    super(title);
    this.midlet = midlet;
    openRecStore();
    this.setCommandListener(this);
         chname = new ChoiceGroup("new", Choice.EXCLUSIVE);
         vecname = new Vector();
         cmdBack = new Command("Back", Command.BACK, 1);
    fmmain = new Form("Record Search");
         addCommand(cmdBack);
    setCommandListener(this);
    readStream();
         rebuildTodoList();
         closeRecStore();
    * Process events for this form only
    protected void rebuildTodoList()
    for(int j=chname.size(); j>0; j--)
         chname.delete(j-1);
         int priority;
         todoitem item;
         String text;
         StringBuffer sb;
         for (int j=0; j<vecname.size(); j++)
              item=(todoitem) vecname.elementAt(j);
              priority = item.getPriority();
              text = item.getText();
              sb = new StringBuffer((flagShowPriority ? (Integer.toString(priority) + "-"): ""));
              sb.append(text);
              chname.append(sb.toString(), null);
    public void commandAction(Command c, Displayable s)
    if (c == cmdBack){
    midlet.displayteledoc();
    public void readStream(){
    try
    byte[] recData=new byte[100];
    String varname;
    int varname1=0;
         ByteArrayInputStream strmBytes = new ByteArrayInputStream(recData);
         DataInputStream strmData=new DataInputStream(strmBytes);
         if (rsperdt.getNumRecords() > 0){
    ComparatorString comp=new ComparatorString();
    int i=1;
              int id = 1;
              vecname.removeAllElements();
              RecordEnumeration re=rsperdt.enumerateRecords(null, comp, false);
    while(re.hasNextElement()){
         rsperdt.getRecord(re.nextRecordId(), recData,0);
    System.out.println("Record #" + i );
    varname = strmData.readUTF();
                   varname1 = strmData.readInt();
                   id = re.nextRecordId();
                   System.out.println("Name #"+varname);
                   todoitem item = new todoitem(varname1, varname, id);
                   vecname.addElement(item);
                   System.out.println("---------------------------");
                   i=i+1;
    strmBytes.reset();
              comp.compareStringClose();
              re.destroy();
    strmBytes.close();
    catch(Exception e){
    System.err.println("read Records class:read");
    public void openRecStore(){
    try{
    rsperdt=RecordStore.openRecordStore("db_per",true);
    catch(RecordStoreException e){
    db(e.toString());
    public void closeRecStore(){
    try{
    rsperdt.closeRecordStore();
    catch(Exception e){
    db(e.toString());
    public void db(String str){
    System.err.println("Msg:" + str);
    class ComparatorString implements RecordComparator{
    private byte[] recData = new byte[20];
    private ByteArrayInputStream strmBytes = null;
    private DataInputStream strmDataType = null;
    public void compareStringClose(){
    try{
    if(strmBytes != null)
         strmBytes.close();
    if(strmDataType != null)
         strmDataType.close();
         catch (Exception e)
    public int compare(byte[] rec1, byte[] rec2)
         String str1, str2;
         try {
              int maxsize = Math.max(rec1.length, rec2.length);
              if (maxsize > recData.length)
              recData = new byte[maxsize];
                   strmBytes = new ByteArrayInputStream(rec1);
                   strmDataType = new DataInputStream(strmBytes);
                   str1=strmDataType.readUTF();
                   strmBytes = new ByteArrayInputStream(rec2);
                   strmDataType = new DataInputStream(strmBytes);
                   str2=strmDataType.readUTF();
                   int result=str1.compareTo(str2);
                   if (result == 0)
                   return RecordComparator.EQUIVALENT;
                   else if (result < 0)
                   return RecordComparator.PRECEDES;
                   else
                   return RecordComparator.FOLLOWS;
                   catch (Exception e)
                   return RecordComparator.EQUIVALENT;

  • How ias integrate with Snacktory for getting main text from an html page

    Hi All,
    i am new to endeca and ias, i have an requirement, need to get main text from whole html page before ias save text to Endeca_Document_Text property,
    as ias save all text in page to endeca_document_text property, it is not ok for reading when show in web page, i use an third party API to filter out the main text from original page,
    now i want to save these text to endeca_document_text property,
    an another question,
    i get zero page when doing the logic of filtering main text from original html text in ParseFilter( HTMLMetatagFilter implements ParseFilter) using Snacktory.
    if only do little things, it will work fine, if do more thing, clawer fail to crawl page. any one know how to fix it.
    log for clawler.
    Successfully set recordstore configuration.
    INFO    2013-09-03 00:56:42,743    0    com.endeca.eidi.web.Main    [main]    Reading seed URLs from: /home/oracle/oracle/endeca/IAS/3.0.0/sample/myfirstcrawl/conf/endeca.lst
    INFO    2013-09-03 00:56:42,744    1    com.endeca.eidi.web.Main    [main]    Seed URLs: [http://www.liferay.com/community/forums/-/message_boards/category/]
    INFO    2013-09-03 00:56:43,497    754    com.endeca.eidi.web.db.CrawlDbFactory    [main]    Initialized crawldb: com.endeca.eidi.web.db.BufferedDerbyCrawlDb
    INFO    2013-09-03 00:56:43,498    755    com.endeca.eidi.web.Crawler    [main]    Using executor settings: numThreads = 100, maxThreadsPerHost=1
    INFO    2013-09-03 00:56:44,163    1420    com.endeca.eidi.web.Crawler    [main]    Fetching seed URLs.
    INFO    2013-09-03 00:56:46,519    3776    com.endeca.eidi.web.parse.HTMLMetatagFilter    [pool-1-thread-1]    come into EndecaHtmlParser getParse
    INFO    2013-09-03 00:56:46,519    3776    com.endeca.eidi.web.parse.HTMLMetatagFilter    [pool-1-thread-1]    come into HTMLMetatagFilter
    INFO    2013-09-03 00:56:46,519    3776    com.endeca.eidi.web.parse.HTMLMetatagFilter    [pool-1-thread-1]    meta tag viewport ==minimum-scale=1.0, width=device-width
    INFO    2013-09-03 00:56:52,889    10146    com.endeca.eidi.web.parse.HTMLMetatagFilter    [pool-1-thread-1]    come into EndecaHtmlParser getParse
    INFO    2013-09-03 00:56:52,889    10146    com.endeca.eidi.web.parse.HTMLMetatagFilter    [pool-1-thread-1]    come into HTMLMetatagFilter
    INFO    2013-09-03 00:56:52,890    10147    com.endeca.eidi.web.parse.HTMLMetatagFilter    [pool-1-thread-1]    meta tag viewport ==minimum-scale=1.0, width=device-width
    INFO    2013-09-03 00:56:59,184    16441    com.endeca.eidi.web.parse.HTMLMetatagFilter    [pool-1-thread-2]    come into EndecaHtmlParser getParse
    INFO    2013-09-03 00:56:59,185    16442    com.endeca.eidi.web.parse.HTMLMetatagFilter    [pool-1-thread-2]    come into HTMLMetatagFilter
    INFO    2013-09-03 00:56:59,185    16442    com.endeca.eidi.web.parse.HTMLMetatagFilter    [pool-1-thread-2]    meta tag viewport ==minimum-scale=1.0, width=device-width
    INFO    2013-09-03 00:57:07,057    24314    com.endeca.eidi.web.parse.HTMLMetatagFilter    [pool-1-thread-2]    come into EndecaHtmlParser getParse
    INFO    2013-09-03 00:57:07,057    24314    com.endeca.eidi.web.parse.HTMLMetatagFilter    [pool-1-thread-2]    come into HTMLMetatagFilter
    INFO    2013-09-03 00:57:07,057    24314    com.endeca.eidi.web.parse.HTMLMetatagFilter    [pool-1-thread-2]    meta tag viewport ==minimum-scale=1.0, width=device-width
    INFO    2013-09-03 00:57:07,058    24315    com.endeca.eidi.web.Crawler    [main]    Seeds complete.
    INFO    2013-09-03 00:57:07,090    24347    com.endeca.eidi.web.Crawler    [main]    Starting crawler shut down
    INFO    2013-09-03 00:57:07,095    24352    com.endeca.eidi.web.Crawler    [main]    Waiting for running threads to complete
    INFO    2013-09-03 00:57:07,095    24352    com.endeca.eidi.web.Crawler    [main]    Progress: Level: Cumulative crawl summary (level)
    INFO    2013-09-03 00:57:07,095    24352    com.endeca.eidi.web.Crawler    [main]    host-summary: www.liferay.com to depth 1
    host    depth    completed    total    blocks
    www.liferay.com    0    0    1    1
    www.liferay.com    1    0    0    0
    www.liferay.com    all    0    1    1
    INFO    2013-09-03 00:57:07,096    24353    com.endeca.eidi.web.Crawler    [main]    host-summary: total crawled: 0 completed. 1 total.
    INFO    2013-09-03 00:57:07,096    24353    com.endeca.eidi.web.Crawler    [main]    Shutting down CrawlDb
    INFO    2013-09-03 00:57:07,160    24417    com.endeca.eidi.web.Crawler    [main]    Progress: Host: Cumulative crawl summary (host)
    INFO    2013-09-03 00:57:07,162    24419    com.endeca.eidi.web.Crawler    [main]   Host: www.liferay.com:  0 fetched. 0.0 mB. 0 records. 0 redirected. 4 retried. 0 gone. 0 filtered.
    INFO    2013-09-03 00:57:07,162    24419    com.endeca.eidi.web.Crawler    [main]    Progress: Perf: All (cumulative) 23.6s. 0.0 Pages/s. 0.0 kB/s. 0 fetched. 0.0 mB. 0 records. 0 redirected. 4 retried. 0 gone. 0 filtered.
    INFO    2013-09-03 00:57:07,162    24419    com.endeca.eidi.web.Crawler    [main]    Crawl complete.
    ~/oracle/endeca
    -======================================
    source code for parsefilter
    package com.endeca.eidi.web.parse;
    import java.util.Map;
    import java.util.Properties;
    import org.apache.hadoop.conf.Configuration;
    import org.apache.log4j.Logger;
    import org.apache.nutch.metadata.Metadata;
    import org.apache.nutch.parse.HTMLMetaTags;
    import org.apache.nutch.parse.Parse;
    import org.apache.nutch.parse.ParseData;
    import org.apache.nutch.parse.ParseFilter;
    import org.apache.nutch.protocol.Content;
    import de.jetwick.snacktory.ArticleTextExtractor;
    import de.jetwick.snacktory.JResult;
    public class HTMLMetatagFilter implements ParseFilter {
        public static String METATAG_PROPERTY_NAME_PREFIX = "Endeca.Document.HTML.MetaTag.";
        public static String CONTENT_TYPE = "text/html";
        private static final Logger logger = Logger.getLogger(HTMLMetatagFilter.class);
        public Parse filter(Content content, Parse parse) throws Exception {
            logger.info("come into EndecaHtmlParser getParse");
            logger.info("come into HTMLMetatagFilter");
            //update the content with the main text in html page
            //content.setContent(HtmlExtractor.extractMainContent(content));
            parse.getData().getParseMeta().add("FILTER-HTMLMETATAG", "ACTIVE");
            ParseData parseData = parse.getData();
            if (parseData == null) return parse;
            extractText(content, parse);
            logger.info("update the content with the main text content");
            return parse;
        private void extractText(Content content, Parse parse){
            try {
                ParseData parseData = parse.getData();
                if (parseData == null) return;
                 Metadata md = parseData.getParseMeta();
                ArticleTextExtractor extractor = new ArticleTextExtractor();
                String sourceHtml = new String(content.getContent());
                JResult res = extractor.extractContent(sourceHtml);
                String text = res.getText();
                md.set("Endeca_Document_Text", text);
            } catch (Exception e) {
                // TODO: handle exception
        public static void log(String msg){
            System.out.println(msg);
        public Configuration getConf() {
            return null;
        public void setConf(Configuration conf) {

    but it only extracts URLs from <A> (anchor) tags. I want to be able to extract URLs from <MAP> tags as wellGee, do you think you could modify the code to check for "Map" attributes as well.
    Can someone maybe point a page containing info on the HTML toolkit for me?It's called the API. Since you are using the HTMLEditorKit and an ElementIterator and an AttributeSet, I would start there.
    There is no such API that says "get me all the links", so you have to do a little work on your own.
    Maybe you could use a ParserCallback and every time you get a new tag you check for the "href" attribute.

  • 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

  • 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.

  • 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?

  • 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.

  • 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

  • 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...

  • RecordStore: multiple stores, deletion and WTK

    Hi All,
    I've been playing around with record stores for a couple of days and have run into a couple of problems, which I think are related.
    First some background. I access the RecordStore methods from a instance of a class called MyRecordStore. In the class there are some methods to open and close stores, retrieve information and set information.
    At first I created a RecordStore called roundStore, which contained the number of rounds of a game that could be played. The store was called "rounds". All was fine!
    The problems started when I defined another RecordStore, called scoreStore:
    protected RecordStore roundStore = null; // works fine
    protected RecordStore scoreStore = null; // problems start here
    //In appropriate try/catch statements
    roundStore = RecordStore.openRecordStore("rounds", true);
    scoreStore = RecordStore.openRecordStore("scores", true);
    ScoreStore was supposed to contain the scores. However, when I ran the WTK I got the following error: javax.microedition.rms.InvalidRecordIDException
    To me it seemed that I could only have one store. However, when I later deleted roundStore (which had been working fine) and then tried to recreate it I got the same message invalidRecordIDException for roundStore. I then listed the stores on my system and both "scores" and "rounds" were listed - even after I thought I deleted them.
    Do the stores persist in the WTK even after they have been deleted and, if so, how can they be removed so that I can start afresh. BTW, I have tried to clean the WTK.
    Thanks if you can provide any help,
    Hugh
    I assume that

    Hi VC,
    Thanks for the information. I've been having problems with the record stores ever since I started deleting them. So I tried your suggestion, but I'm afraid no joy.
    I've even gone right back to the start, to where I thought that all was well and I'm still getting an "InvalidRecordIDException".
    To explain: I create an instance of MyRecordStore. In the MyRecordStore class I create an instance of the RecordStore class:
    RecordStore roundStore = null;
    Later on I open it, and create it if required
    protected void openRounds(){
         try
                   roundStore = RecordStore.openRecordStore("rounds", true);
              catch (RecordStoreException rse) {
                   System.out.println("RSE " + rse);
                   rse.printStackTrace();
    }//end of openRounds
    No exceptions yet. However, if I try to set a record an InvalidRecordIDException is thrown (b is a byte array):
    try {
                   recId = roundStore.getNextRecordID();
                   System.out.println("getNum " + String.valueOf(recId));
                   roundStore.setRecord(1, b, 0, b.length);// this line is the problem
    I can interrogate the store to get the next record ID, which returns 1.
    If anyone has any ideas on why I'm getting this error I would be pleased to hear from you.
    Many thanks,
    Hugh

Maybe you are looking for

  • Is there a way to authorize more than 5 computers.  We have three macs and 5 pc's in the house.

    Hello,  I have a MBP (mid 12 model), a brand new MBA (mid 13), and Mac Mini, four laptop PCs and 2 more Desktop PCs (I have teenage daughters and my wife)... I intend for one of the PC's to be a "server" I have a large library that certainly does not

  • Photoshop CS2 keeps crashing on MacBook Pro running snow leopard

    I have been using CS2 on my MacBook Pro for more than two years.  Just two days ago, the Photoshop application began to UNEXPECTEDLY QUIT every time I opened it.  All other apps in the CS2 are working fine.  I have NEVER had a problem with the CS2 or

  • Cant restore my apple id on my ipad

    hi i gave my ipod to my daughter and reset it to her e mail but after that i cant use my apple id on my ipad and mail not work on my iphone and both display username and pass word not matched i tried id manger can not help as either say this email is

  • When Try to Watch a Video...

    When i try to watch a video all that shows up are boxes of the immage supposed to be and white lines on te bottom of the screen when i roll over it. Anyone with the same problem... Help.

  • VM Heap Memory

    Forgive my ignorance, but why is it that we have to manually set the amount of memory we want to allocate to the VM with the -Xmx command? Why can't the VM allocate more memory when it needs to? When trying to work with Java imaging programs that req