/* * rmsHandler.java * Created by: Csaba Kopias with the help of the #j2me guys at irc.freenode.net * Licence: GPL, be sure how you use it, it's my first j2me code:D * Created on October 28, 2007, 1:06 PM * */ package mmc; import java.io.*; import javax.microedition.rms.*; /** * * @author meta */ public class rmsHandler { private RecordStore _rs; private String[] _db = new String[32]; private boolean we_are_opened = false; public rmsHandler(String db) { byte[] data = null; int i = 0; int size; String foo; try { _rs = RecordStore.openRecordStore(db, true); we_are_opened = true; } catch (RecordStoreException ex) { ex.printStackTrace(); we_are_opened = false; } try { RecordEnumeration re = _rs.enumerateRecords(null, null, true); if (_rs.getNumRecords() > 0) { /* get the first record */ data = re.nextRecord(); if (data != null) { ByteArrayInputStream bin; DataInputStream din; bin = new ByteArrayInputStream(data); din = new DataInputStream(bin); //size = din.readInt(); //_db = new String[size]; while (din.available() > 0) { _db[i] = din.readUTF(); } } } } catch (Exception e) { e.printStackTrace(); } } public void saveDb() { int recordID; int i = 1; if (!we_are_opened) { return; } try { RecordEnumeration re = _rs.enumerateRecords(null, null, true); if (re.numRecords() > 0) { recordID = re.nextRecordId(); } else { recordID = _rs.addRecord(null, 0, 0); System.out.println("UJ REKORD"); } } catch (Exception ex) { ex.printStackTrace(); } ByteArrayOutputStream bout = new ByteArrayOutputStream(); DataOutputStream dout = new DataOutputStream(bout); try { // dout.writeInt(_db.length); System.out.println("Most kene tarolni..."+_db.length); for (i = _db.length; i > 0; i--) { if(_db[i - 1]!=null) { dout.writeUTF(_db[i - 1]); System.out.println("Tarolas: "+i+":"+_db[i-1]); } } dout.close(); byte[] data = bout.toByteArray(); _rs.addRecord(data, 0, data.length); } catch (Exception e) { // handle RMS error here e.printStackTrace(); } try { _rs.closeRecordStore(); we_are_opened = false; System.out.println("RSKLOZD"); //recordStore.deleteRecordStore(RECORD_STORE_NAME); } catch (RecordStoreException rse) { System.err.println(rse.toString()); } } public void set(String key, String val) { String most; boolean vanMar = false; int elso = -1; if (!we_are_opened) { return; } for (int i = _db.length; i > 0; i--) { most = _db[i - 1]; if (most != null && most.substring(0, most.indexOf(":")).equals(key)) { _db[i - 1] = key + ":" + val; vanMar = true; break; } if (elso == -1 && most != null) { elso = i; } } if (!vanMar) { _db[elso + 1] = key + ":" + val; } } public String get(String key) { String most; for (int i = _db.length; i > 0; i--) { most = _db[i - 1]; if (most != null && most.substring(0, most.indexOf(":")).equals(key)) { return most.substring(most.indexOf(":") + 1, most.length()); } } return null; } }