Hej Lasse,
Her er en klasse som kan gemme en streng + int-værdi på en mobil-tlf.
package example.LiveScore;
import java.lang.System;
import java.lang.Runnable;
import java.lang.InterruptedException;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreException;
public class db
{
private static int[] dbInt;
private static String[] dbString;
private static RecordStore myStore;
private static boolean dbInitialized;
private static int dbSize = 0;
private static int dbUsed = 0;
public db(int MaxEntries)
{
dbInitialized = false;
dbSize = MaxEntries;
dbInt = new int[dbSize];
dbString = new String[dbSize];
}
static void openDB(String db_name)
{
try
{
myStore = RecordStore.openRecordStore(db_name, true);
dbInitialized = true;
if ((dbUsed = myStore.getNumRecords()) > 0)
{ // okay, data is available.
ByteArrayInputStream bais;
DataInputStream dis;
byte data[];
for (int i = 0; i < dbUsed; i++)
{
data = myStore.getRecord(i+1);
if (data != null)
{
try
{
bais = new ByteArrayInputStream(data);
dis = new DataInputStream(bais);
dbInt[i] = dis.readInt();
dbString[i] = dis.readUTF();
dis.close();
}
catch (IOException ioe)
{
}
}
}
}
}
catch (RecordStoreException rse)
{
}
}
static void closeDB()
{
if (myStore != null)
{
try
{
myStore.closeRecordStore();
}
catch (RecordStoreException frse)
{
}
myStore = null;
dbInitialized = false;
}
}
static void updateDB(int id, int newInt, String newString) throws RecordStoreException
{
ByteArrayOutputStream baos;
DataOutputStream das;
byte[] data;
if ((id < dbSize) && (dbInitialized))
{
try
{
baos = new ByteArrayOutputStream();
das = new DataOutputStream(baos);
das.writeInt(newInt);
das.writeUTF(newString);
data = baos.toByteArray();
das.close();
}
catch (IOException ioe)
{
throw new RecordStoreException();
}
try
{
myStore.setRecord(id, data, 0, data.length);
}
catch (RecordStoreException rse)
{ // ups record not found so insert enstead.
myStore.addRecord(data, 0, data.length);
}
dbInt[id] = newInt;
dbString[id] = newString;
}
}
static int getDBInt(int id)
{
if ((id < dbSize) && (dbInitialized))
return dbInt[id];
return -1;
}
static String getDBString(int id)
{
if ((id < dbSize) && (dbInitialized))
return dbString[id];
return null;
}
}
og her er hvordan du bruger koden:
db myDatabase = new db(10);
myDatabase.openDB("myNewStore");
try
{
myDatabase.updateDB(0, 100, "First entry");
myDatabase.closeDB();
}
catch(Exception e)
{
myDatabase.closeDB();
}
myDatabase.openDB("myNewStore");
String test = myDatabase.getDBString(0);
myDatabase.closeDB();
myDatabase = null;
mvh
Michael.