Monday, April 30, 2012

URLEncoder for Encoding URL


import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;

public class URLEncoder {
        public static String encode(String s, String enc) throws IOException {
            ByteArrayOutputStream bOut = new ByteArrayOutputStream();
            DataOutputStream dOut = new DataOutputStream(bOut);
            StringBuffer ret = new StringBuffer(); // return value
            dOut.writeUTF(s);
            ByteArrayInputStream bIn = new ByteArrayInputStream(bOut.toByteArray());
            bIn.read();
            bIn.read();
            int c = bIn.read();
            while (c >= 0) {
                if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')
                        || (c >= '0' && c <= '9') || c == '.' || c == '-'
                        || c == '*' || c == '_') {
                    ret.append((char) c);
                } else if (c == ' ') {
                    ret.append('+');
                } else {
                    if (c < 128) {
                        appendHex(c, ret);
                    } else if (c < 224) {
                        appendHex(c, ret);
                        appendHex(bIn.read(), ret);
                    } else if (c < 240) {
                        appendHex(c, ret);
                        appendHex(bIn.read(), ret);
                        appendHex(bIn.read(), ret);
                    }
                }
                c = bIn.read();
            }
            return ret.toString();
        }

        private static void appendHex(int arg0, StringBuffer buff) {
            buff.append('%');
            if (arg0 < 16) {
                buff.append('0');
            }
            buff.append(Integer.toHexString(arg0));
        }
}

Tuesday, June 14, 2011

Java Math Functions which are not available in J2ME

package com.huayu.gps;

public class Deg {

    public static final int SEC = 500;
    public static final int MIN = 60 * SEC;
    public static final int DEG = 60 * MIN;

    public static final int FORMAT_AUTO = -1;
    public static final int FORMAT_D = 0;
    public static final int FORMAT_DM = 1;
    public static final int FORMAT_DMS = 2;
    public static final int FORMAT_NMEA = 3;
    public static final int FORMAT_FIXED = 4;

    public static final int PRECISION_D = 6;
    public static final int PRECISION_M = 4;
    public static final int PRECISION_S = 2;

    // fixed decimal point = 1
    public static final int iFIXED = 1000; // Integer.MAX_VALUE;
    //public static final long FIXED = Long.MAX_VALUE;

    private static int format = FORMAT_D;

    protected int deg;

    public Deg() { this.deg = 0; }
    public Deg( int deg ) { this.deg = limitDeg( deg ); }
    public Deg( long deg ) { this.deg = limitDeg( deg ); }
    public Deg( Deg deg ) { this.deg = deg.deg; }

    public void set( int deg ) { this.deg = limitDeg( deg ); }
    public void set( long deg ) { this.deg = limitDeg( deg ); }
    public void set( Deg deg ) { this.deg = deg.deg; }

    public int get() { return deg; }
    public String toString() {
        return "";    // TODO
    }

    public static void setFormat( int f ) { format = f; }
    public static int getFormat() { return format; }

    public static int min( int a, int b ) {
        return ( a < b ) ? a : b;
    }

    public static int max( int a, int b ) {
        return ( a > b ) ? a : b;
    }

    public static int abs( int x ) {
        return ( x < 0 ) ? -x : x;
    }

    public static int limitDeg( int deg ) {
        while( deg >= 360 * DEG ) deg -= 360 * DEG;
        while( deg < 0 ) deg += 360 * DEG;
        return deg;
    }

    public static int limitDeg( long deg ) {
        while( deg >= 360 * DEG ) deg -= 360 * DEG;
        while( deg < 0 ) deg += 360 * DEG;
        return (int) deg;
    }

    public static int limitDeg( double deg ) {
        while( deg >= 360 * DEG ) deg -= 360 * DEG;
        while( deg < 0 ) deg += 360 * DEG;
        return (int) deg;
    }

    public static String degToStr( int value, int f, int n, int precision, String signPlus, String signMinus ) {
        StringBuffer tmpsb = new StringBuffer();
        if( ( ( f < 0 ) ? format : f ) != FORMAT_FIXED ) {
            tmpsb.append( ( value < 0 ) ? signMinus : signPlus );
            value = ( value < 0 ) ? -value : value;
        }
        switch( ( f < 0 ) ? format : f ) {
            case FORMAT_FIXED :
            case FORMAT_D :
                tmpsb.append( VlkText.fixToStr( value, DEG, n, ( precision < 0) ? PRECISION_D : precision ) );
                break;
            case FORMAT_DM :
                tmpsb.append( VlkText.intToStr( value / DEG, n ) );
                tmpsb.append( "°" );
                tmpsb.append( VlkText.fixToStr( value % DEG, MIN, 2, ( precision < 0) ? PRECISION_M : precision ) );
                break;
            case FORMAT_DMS :
                tmpsb.append( VlkText.intToStr( value / DEG, n ) );
                tmpsb.append( "°" );
                tmpsb.append( VlkText.intToStr( ( value % DEG ) / MIN, 2 ) );
                tmpsb.append( "'" );
                tmpsb.append( VlkText.fixToStr( value % MIN, SEC, 2, ( precision < 0) ? PRECISION_S : precision ) );
                break;
        }
        return tmpsb.toString();
    }

    public static int strToDeg( String value ) {
        int idp = value.indexOf( '.' );
        int idk = value.indexOf( ',' );              
        int igr = value.indexOf( "°" );
        int imn = value.indexOf( "'" );
        if( imn > igr ) {
            // FORMAT_DMS // DDD°MM'SS.ss // TODO rewrite to int
            int tmpi = Integer.parseInt( value.substring( 0, igr ) ) * DEG;
            tmpi += Integer.parseInt( value.substring( igr + 1, imn ) ) * MIN;
            tmpi += (int) ( Double.parseDouble( value.substring( imn + 1 ) ) * SEC );
            return tmpi;
        }
        if( igr > 0 ) {
            // FORMAT_DM // DDD°MM.mmmm // TODO rewrite to int
            int tmpi = Integer.parseInt( value.substring( 0, igr ) ) * DEG;
            tmpi += (int) ( Double.parseDouble( value.substring( igr + 1 ) ) * MIN );
            return tmpi;
        }
        if( ( idp == 4 ) || ( idp == 5 ) ) {
            // FORMAT_NMEA // DDDMM.mmmm
            int tmpi = Integer.parseInt( value.substring( 0, idp - 2 ) ) * DEG;
            tmpi += (int) ( Double.parseDouble( value.substring( idp - 2 ) ) * MIN );
//            tmpi += Integer.parseInt( value.substring( idp - 2, idp ) ) * MIN;
//            tmpi += Integer.parseInt( value.substring( idp + 1 ) ) * ( MIN / 10000 );
            return tmpi;
        }
        if( ( idp >= 0 ) && ( idp <= 3 ) ) {
            // FORMAT_D // DDD.dddddd
            double tmpd = Double.parseDouble( value );
            return degToInt( tmpd );
        }
        if( ( idk >= 0 ) && ( idk <= 3 ) ) {
            // FORMAT_D // DDD,dddddd
            double tmpd = Double.parseDouble( value.replace(',','.') );
            return degToInt( tmpd );
        }
        // FORMAT_ERROR
        return 0; // make exception!
    }

    public static int degToInt( double deg ) {
        return( (int) ( deg * DEG ) );
    }

    public static double sqr( double x ) {
        return ( x * x );
    }

    public static int asin( double x ) {
        return (int)( (double)DEG * Math.toDegrees( Float11.asin( x ) ) );
    }

//    public static int asin( long x ) {
//        return (int)( (double)DEG * Math.toDegrees( Float11.asin( ( (double)x ) / FIXED ) ) );
//    }

    public static int acos( double x ) {
        return (int)( (double)DEG * Math.toDegrees( Float11.acos( x ) ) );
    }

//    public static int acos( long x ) {
//        return (int)( (double)DEG * Math.toDegrees( Float11.acos( ( (double)x ) / FIXED ) ) );
//    }

    public static int atan( double x ) {
        return (int)( (double)DEG * Math.toDegrees( Float11.atan( x ) ) );
    }

    public static int atan2( double y, double x ) {
        return (int)( (double)DEG * Math.toDegrees( Float11.atan2( y, x ) ) );
    }

    public static double sin( int x ) {
        return Math.sin( Math.toRadians( ( (double) x ) / DEG ) );
    }

    public static double cos( int x ) {
        return Math.cos( Math.toRadians( ( (double) x ) / DEG ) );
    }

    private static int[] tabSin = new int[ 720 ];
    private static boolean mathTablesCreated = false;

    public static int fastSin( int x ) {
        return( tabSin[ limitDeg( x ) / ( DEG / 2 ) ] );
    }

    public static int fastCos( int x ) {
        x += 90 * DEG;
        return( tabSin[ limitDeg( x ) / ( DEG / 2 ) ] );
    }

    public static void initFastMath() {
        if( ! mathTablesCreated ) {
            //Debug.debug( "Generating fast math tables" );
            for( int i = 0; i < 720; i++ ) {
                tabSin[ i ] = ( int ) ( iFIXED * Math.sin( Math.toRadians( i / 2 ) ) );
            }
            mathTablesCreated = true;
        }
    }

    public static void mathBench() {
        //Debug.debug( "Math speed test:" );
        int j = 0;
        long drawTime = System.currentTimeMillis();
        for( int i = 0; i < 1000; i++, j += MIN ) {
            sin( j );
        }
        //Debug.debug( "sin(): " + (int)( System.currentTimeMillis() - drawTime ) + "us" );
        j = 0;
        drawTime = System.currentTimeMillis();
        for( int i = 0; i < 1000; i++, j += MIN ) {
            cos( j );
        }
        //Debug.debug( "cos(): " + (int)( System.currentTimeMillis() - drawTime ) + "us" );
        j = 0;
        drawTime = System.currentTimeMillis();
        for( int i = 0; i < 1000; i++, j += MIN ) {
            asin( j );
        }
        //Debug.debug( "asin(): " + (int)( System.currentTimeMillis() - drawTime ) + "us" );
        j = 0;
        drawTime = System.currentTimeMillis();
        for( int i = 0; i < 1000; i++, j += MIN ) {
            acos( j );
        }
        //Debug.debug( "acos(): " + (int)( System.currentTimeMillis() - drawTime ) + "us" );
        j = 0;
        drawTime = System.currentTimeMillis();
        for( int i = 0; i < 1000; i++, j += MIN ) {
            fastSin( j );
        }
        //Debug.debug( "fastSin(): " + (int)( System.currentTimeMillis() - drawTime ) + "us" );
        j = 0;
        drawTime = System.currentTimeMillis();
        for( int i = 0; i < 1000; i++, j += MIN ) {
            fastCos( j );
        }
        //Debug.debug( "fastCos(): " + (int)( System.currentTimeMillis() - drawTime ) + "us" );
        Coords wpt1 = new Coords( 10 * DEG, 30 * DEG, 0 );
        Coords wpt2 = new Coords( 20 * DEG, 70 * DEG, 0 );
        drawTime = System.currentTimeMillis();
        for( int i = 0; i < 1000; i++ ) {
            j = wpt1.zenith( wpt2 );
        }
        //Debug.debug( "zenith(): " + (int)( System.currentTimeMillis() - drawTime ) + "us" );
        drawTime = System.currentTimeMillis();
        int k = j;
        for( int i = 0; i < 1000; i++ ) {
            j = wpt1.azimuth( wpt2, k );
        }
        //Debug.debug( "azimuth(): " + (int)( System.currentTimeMillis() - drawTime ) + "us" );
    }

}

Thursday, June 9, 2011

Compressor Decompressor Class


import java.io.IOException;
import java.io.ByteArrayOutputStream;

public class Compressor {
   
    /* Tailored to int as 32bit signed */
    private final static int FIRST_QUARTER = 0x200000;
    private final static int THIRD_QUARTER = 0x600000;
    private final static int HALF          = 0x400000;
    private final static int HIGH          = 0x7fffff;
    private final static int INITIAL_READ  = 23;
   
    public static byte[] compress(byte[] in) {
       
        class BitOutputBuffer {
            ByteArrayOutputStream buf;
            byte[] currentByte;
            byte currentBit;
            BitOutputBuffer() {
                buf = new ByteArrayOutputStream();
                currentByte = new byte[1];
                currentByte[0] = 0;
                currentBit = 0;
            }
            void writeBit(byte bit) throws IOException {
                currentByte[0] = (byte) ((currentByte[0]) << 1);
                currentByte[0] += bit;
                currentBit+=1;
                if (currentBit==8) {
                    buf.write(currentByte);
                    currentByte[0] = 0;
                    currentBit = 0;
                }
            }
            void flush() throws IOException {
                /* Pad the buffer with zeros */
                while (currentBit!=0) {
                    writeBit((byte) 0);
                }
                buf.flush();
            }
           
            byte[] toByteArray() {
                try {
                    buf.flush();
                    return buf.toByteArray();
                }
                catch (IOException e) {
                    return null;
                }
            }
           
        }
       
        BitOutputBuffer bitBuf = new BitOutputBuffer();
       
        int low = 0, high = HIGH, total;
        int mLow = low, mHigh = high, mStep = 0;
        int mScale = 0;
        int current = 0;
       
        /* Initialize frequency table */
        int[] freq = new int[257];
        for (int i=0; i<257; i++) freq[i] = 1;
        total = 257;
       
        try {
           
            for (int i=0; i<in.length + 1; i++) {
               
                if (i == in.length) {
                    /* Encode terminator if necessary */
                    low = total - 1;
                    high = total;
                }
                else {
                    /* Otherwise retrieve cumulative freq */
                    current = in[i] & 0xff; // Get unsigned value
                    low = 0;
                    for (int j=0; j<current; j++) {
                        low += freq[j];
                    }
                    high = low + freq[current];
                }
               
                /* 2. Update the coder */
                mStep = ( mHigh - mLow + 1 ) / total;
                mHigh = (mLow + mStep * high) - 1;
                mLow = mLow + mStep * low;
               
                /* Renormalize if possible */
                while( (mHigh < HALF) || (mLow >= HALF) )
                {
                    if( mHigh < HALF )
                    {
                        bitBuf.writeBit((byte) 0);
                        mLow = mLow * 2;
                        mHigh = mHigh * 2 + 1;
                       
                        /* Perform e3 mappings */
                        for(; mScale > 0; mScale-- )
                            bitBuf.writeBit((byte) 1);
                    }
                    else if( mLow >= HALF )
                    {
                        bitBuf.writeBit((byte) 1);
                        mLow = ( mLow - HALF ) * 2;
                        mHigh = ( mHigh - HALF ) * 2 + 1;
                       
                        /* Perform e3 mappings */
                        for(; mScale > 0; mScale-- )
                            bitBuf.writeBit((byte) 0);
                    }
                }
               
                while((FIRST_QUARTER <= mLow) && (mHigh < THIRD_QUARTER)) {
                    mScale++;
                    mLow = ( mLow - FIRST_QUARTER ) * 2;
                    mHigh = ( mHigh - FIRST_QUARTER ) * 2 + 1;
                }       
               
                /* 3. Update model */
                freq[current]+=1;
                total+=1;
               
            }
            /* Finish encoding */
            if( mLow < FIRST_QUARTER ) {
                /* Case: mLow < FirstQuarter < Half <= mHigh */
                bitBuf.writeBit((byte) 0);
                /* Perform e3-scaling */
                for( int i=0; i<mScale+1; i++ )
                    bitBuf.writeBit((byte) 1);
            } else {
                /* Case: mLow < Half < ThirdQuarter <= mHigh */
                bitBuf.writeBit((byte) 1 );
            }
            bitBuf.flush();
        }
        catch (IOException e) {
            return null;
        }
        return bitBuf.toByteArray();
    }
   
    public static byte[] decompress(byte[] in) {
       
        class BitInputBuffer {
            byte[] source;
            int bytep = 0, bitp = 0;
            byte currentByte = 0;
            BitInputBuffer(byte [] source) {
                this.source = source;
                currentByte = source[0];// & 0xff;
            }
            int readBit() {
                int result = (currentByte >> 7) & 1;
                currentByte = (byte) (currentByte << 1);
                if (bitp++==7) {
                    bytep++;
                    if (bytep > source.length - 1) {
                        currentByte = 0;
                    }
                    else {
                        currentByte = source[bytep];
                        bitp = 0;
                    }
                }
                return result;
            }
        }
       
        ByteArrayOutputStream buf = new ByteArrayOutputStream();
        /* Initialise frequency table */
       
        int[] freq = new int[257];
        for (int i=0; i<257; i++) freq[i] = 1;
        int total = 257;
        int current = 0;
        int value;
        int low = 0, high = HIGH;
        int mLow = low, mHigh = high, mStep = 0, mScale = 0, mBuffer = 0;
        BitInputBuffer inbuf = new BitInputBuffer(in);
        /*    Fill buffer with bits from the input stream */

        for( int i=0; i<INITIAL_READ; i++ ) {
            mBuffer = 2 * mBuffer;
            mBuffer += inbuf.readBit();
        }
           
        while(true) {
            /* 1. Retrieve current byte */
            mStep = ( mHigh - mLow + 1 ) / total;
            value = ( mBuffer - mLow ) / mStep;
            low = 0;
            for (current=0; current<256 && low + freq[current] <= value; current++)
                low += freq[current];
           
            if (current==256) break;
           
            buf.write(current);
            high = low + freq[current];
           
            /* 2. Update the decoder */
            mHigh = mLow + mStep * high - 1; // interval open at the top => -1
           
            /* Update lower bound */
            mLow = mLow + mStep * low;
           
            /* e1/e2 mapping */
            while( ( mHigh < HALF ) || ( mLow >= HALF ) )
            {
                if( mHigh < HALF )
                {
                    mLow = mLow * 2;
                    mHigh = ((mHigh * 2) + 1);
                    mBuffer = (2 * mBuffer);
                }
                else if( mLow >= HALF )
                {
                    mLow = 2 * ( mLow - HALF );
                    mHigh = 2 * ( mHigh - HALF ) + 1;
                    mBuffer = 2 * ( mBuffer - HALF );
                }
   
                mBuffer += inbuf.readBit();
                mScale = 0;
            }
           
            /* e3 mapping */
            while( ( FIRST_QUARTER <= mLow ) && ( mHigh < THIRD_QUARTER ) )
            {
                mScale++;
                mLow = 2 * ( mLow - FIRST_QUARTER );
                mHigh = 2 * ( mHigh - FIRST_QUARTER ) + 1;
                mBuffer = 2 * ( mBuffer - FIRST_QUARTER ) ;
                mBuffer += inbuf.readBit();
            }
           
            /* 3. Update frequency table */
            freq[current]+=1;
            total+=1;
        }
       
        return buf.toByteArray();
    }
}

Push Registry (Calling one application from other)

Code for Midlet 1 which will call Midlet2

import java.io.IOException;
import javax.microedition.io.Connector;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Form;
import javax.microedition.midlet.*;

/**
 * @author root
 */
public class pushmid extends MIDlet {
    public void startApp() {

        Form f = new Form("Hii");
        Display d = Display.getDisplay(this);

        try {
            f.append("PushApp");
            d.setCurrent(f);
            Connector.open("socket://127.0.0.1:7777");
        } catch (IOException ex) {
            ex.printStackTrace();
        }
       
    }

    public void pauseApp() {
    }

    public void destroyApp(boolean unconditional) {
    }
}





.Jad file attributes for Midlet 2

MIDlet-1: newApp, , newApp
MIDlet-Jar-Size: 1066
MIDlet-Jar-URL: PushSample2.jar
MIDlet-Name: PushSample2
MIDlet-Push-1: socket://:7777,newApp,*
MIDlet-Vendor: Vendor
MIDlet-Version: 1.0
MicroEdition-Configuration: CLDC-1.1
MicroEdition-Profile: MIDP-2.0





and code in Midlet 2

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

import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Form;
import javax.microedition.midlet.*;

/**
 * @author root
 */
public class newApp extends MIDlet {
    Form f = new Form("Hii");
    Display d = Display.getDisplay(this);
    public void startApp() {
        f.append("newApp");
        d.setCurrent(f);
    }

    public void pauseApp() {
    }

    public void destroyApp(boolean unconditional) {
    }
}


This way Midlet 2 will be invoke when starting Midlet 1

XML Parsing With SAXParser


import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Vector;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;


public class LocalDataObject {

    private int noOfFields;
    private Vector recordValues = null;
    private int tblCode = 0;
    private String tblName;
    private static SAXParserFactory factory = null;
    private SAXParser saxParser = null;

    public LocalDataObject(int tblCode) {
        this.tblCode = tblCode;
        tblName = ConstantCodes.TBL_NAMES[tblCode];
        this.noOfFields = ConstantCodes.FLD_NAMES[this.tblCode].length;
        recordValues = new Vector();
        recordValues.setSize(noOfFields);

    }

    public LocalDataObject(int tblCode, String socId) {
        this(tblCode);
        if (tblCode == ConstantCodes.TBL_CUSTOMERDETAILS_CODE) {
            tblName = ConstantCodes.TBL_NAMES[ConstantCodes.TBL_CUSTOMERDETAILS_CODE];
        }
        tblName += socId;
    }

    public void setValue(int fieldIndex, String value) {
        if (fieldIndex < noOfFields) {
            recordValues.setElementAt(value, fieldIndex);
        }
    }

    public String getValue(int fieldValue) {
        return (String) recordValues.elementAt(fieldValue);
    }

    public boolean loadDataFromID(int rmsID) {
        RMSStore tempStore = new RMSStore();
        tempStore.openRecordStore(tblName);

        boolean dataLoaded = false;

        try {
            String xmlString = new String(tempStore.getRecordByteFromId(rmsID));
            if (xmlString != null) {
                dataLoaded = setValuesFromXML(xmlString);
            } else {
                dataLoaded = false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            dataLoaded = false;
        } finally {
            tempStore.closeRecordStore();
        }
        return dataLoaded;
    }

    static {
        try {
            factory = SAXParserFactory.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public boolean setValuesFromXML(String xml) {
        InputStream is = null;
        try {
            XMLHandler handler = new XMLHandler();
            handler.setParameters(noOfFields, recordValues);
            is = new ByteArrayInputStream(xml.getBytes());
            InputSource inputSource = new InputSource(is);
            saxParser = factory.newSAXParser();
            saxParser.parse(inputSource, handler);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public String toString() {
        StringBuffer buffer = new StringBuffer();

        buffer.append("<ROW>");
        for (int i = 0; i < noOfFields; i++) {

            buffer.append("<");
            buffer.append(ConstantCodes.FLD_NAMES[tblCode][i]);
            buffer.append(">");

            buffer.append(getValue(i));

            buffer.append("</");
            buffer.append(ConstantCodes.FLD_NAMES[tblCode][i]);
            buffer.append(">");
        }
        buffer.append("</ROW>");

        return buffer.toString();
    }

    public static Vector getXMLRecords(String xml) {
        String record = null;
        String rec = "</ROW>";
        Vector vRec = new Vector();
        int index = 0;
        while (true) {
            index = xml.indexOf(rec);
            if (index == -1) {
                break;
            }
            record = xml.substring(0, index + rec.length());
            vRec.addElement(record);
            xml = xml.substring(record.length());
        }
        record = null;

        return vRec;
    }


    static class XMLHandler extends DefaultHandler {

        Vector xmlRecord = null;
        int count = 0;
        int noOfFields;

        private void setParameters(int noOfFields, Vector recordValues) {
            this.noOfFields = noOfFields;
            this.xmlRecord = recordValues;
        }

        public void startDocument() throws SAXException {

            xmlRecord.removeAllElements();
            xmlRecord.setSize(noOfFields);
        }

        public void startElement(String uri, String localName, String qName,
                Attributes attributes) throws SAXException {
        }

        public void characters(char[] ch, int start, int length)
                throws SAXException {

            xmlRecord.setElementAt(new String(ch, start, length).trim(), count);
            count += 1;
        }

        public void endElement(String uri, String localName, String qName)
                throws SAXException {
        }

        public void endDocument() throws SAXException {
        }
    }
}

RMS Management


import java.util.Enumeration;
import java.util.Vector;
import javax.microedition.rms.RecordEnumeration;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreException;
import javax.microedition.rms.RecordStoreFullException;
import javax.microedition.rms.RecordStoreNotOpenException;


public class RMSStore {

    private RecordStore rs = null;

    public void openRecordStore(String str) {
        try {
            if (rs == null) {
                rs = RecordStore.openRecordStore(str, true);
                //Modified by Mihir
                //rs = RecordStore.openRecordStore(str, true,RecordStore.AUTHMODE_ANY,true);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void closeRecordStore() {
        try {
            if (rs != null) {
                rs.closeRecordStore();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void deleteRecordStore(String storenName) {
        try {
            RecordStore.deleteRecordStore(storenName);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String[] listAllRecordStore() {
        return RecordStore.listRecordStores();
    }

    public int writeRecord(String str) {
        int id = 0;
        try {
            id = rs.addRecord(str.getBytes(), 0, str.getBytes().length);
        } catch (RecordStoreFullException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return id;
    }

    public int writeByteRecord(byte[] data) {
        int id = -1;

        try {
            id = rs.addRecord(data, 0, data.length);
        } catch (RecordStoreFullException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return id;
    }

    public int getRecordCount() {
        try {
            return rs.getNumRecords();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    public byte[] getRecordDataFromId(int id) {
        byte[] data = null;
        try {
            data = rs.getRecord(id);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return data;
    }

    public String getRecordFromId(int id) {
        return new String(getRecordDataFromId(id));
    }

    public byte[] getRecordByteFromId(int id) {
        return getRecordDataFromId(id);
    }

    public void deleteRecord(int id) {
        try {
            rs.deleteRecord(id);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public boolean checkRecordExists(String compare) {
        for (int i = 0; i < getRecordCount(); i++) {
            if (compare.equals(getRecordFromId(i + 1))) {
                return true;
            }
        }
        return false;
    }

    public int getMaxRMSSize() {
        int size = 0;
        try {
            size = rs.getSizeAvailable() + rs.getSize();
        } catch (RecordStoreNotOpenException e) {
            e.printStackTrace();
        }

        return size;
    }

    public void setRecordById(String str, int id) {
        try {
            rs.setRecord(id, str.getBytes(), 0, str.getBytes().length);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public int getNextRecordId() {
        int id = 0;
        try {
            id = rs.getNextRecordID();
        } catch (RecordStoreException re) {
            re.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return id;
    }

    public RecordEnumeration getRecordEnumData() {
        try {
            return rs.enumerateRecords(null, null, false);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public String[] getRecordData() {

        String[] str = null;
        int counter = 0;
        try {
            RecordEnumeration enumeration = rs.enumerateRecords(null, null, false);
            str = new String[rs.getNumRecords()];

            while (enumeration.hasNextElement()) {
                try {
                    str[counter] = (new String(enumeration.nextRecord()));
                    counter++;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return str;
    }

}

Sample Form Singleton


import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.TextField;


public class RFIDVerificationForm extends CustomForm {

    private TextField txtRFIDNo = null;
    private Command cmdVerify = null;
    private Command cmdBack = null;

    private static RFIDVerificationForm thisForm;
    private static RFIDVerificationFormListener listener;

    public RFIDVerificationForm() {
        super();
        thisForm = this;
        initComponents();
        addComponents();
    }

    protected void initComponents() {

        txtRFIDNo = new TextField("Enter RFID No", "", 20, TextField.ANY);
        cmdVerify = new Command("OK", Command.ITEM, 1);
        cmdBack = new Command("Back", Command.BACK, 1);

    }

    protected void addComponents() {

        append(txtRFIDNo);
        addCommand(cmdVerify);
        addCommand(cmdBack);
        setCommandListener(getListener());
    }

    private RFIDVerificationFormListener getListener() {
        if (listener == null) {
                listener = new RFIDVerificationFormListener();
        }
        return listener;
    }

    public static RFIDVerificationForm getInstance() {

        if (thisForm == null) {
                thisForm = new RFIDVerificationForm();
        }
        thisForm.txtRFIDNo.setString("");
        return thisForm;
    }

    private class RFIDVerificationFormListener implements CommandListener {
        public void commandAction(Command cmd, Displayable displayable) {

            if (cmd.getLabel().equals("Back")) {
                thisForm.prevForm.setAsDisplay();
            }
            else if (cmd.getLabel().equals("OK")) {                   
               
           }
        }
    }
}