//DataRecordStoreTest.java
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.rms.* ;
import java.io.*;
class FriendData
{
String name ;
String tel ;
boolean sex ;
int age ;
public FriendData()
{
name = "NO NAME" ;
name = "NO TEL" ;
sex = false ;
age = 0 ;
}
public byte[] encode()
{
byte[] result = null ;
try
{
ByteArrayOutputStream bos =
new ByteArrayOutputStream() ;
DataOutputStream dos =
new DataOutputStream (bos) ;
dos.writeUTF(name) ;
dos.writeUTF(tel) ;
dos.writeBoolean(sex) ;
dos.writeInt(age) ;
result = bos.toByteArray() ;
dos.close() ;
bos.close() ;
}
catch(Exception e)
{ }
return result ;
}
public void decode(byte[] data)
{
try
{
ByteArrayInputStream bis =
new ByteArrayInputStream(data) ;
DataInputStream dis =
new DataInputStream (bis) ;
name = dis.readUTF() ;
tel = dis.readUTF() ;
sex = dis.readBoolean() ;
age = dis.readInt() ;
dis.close() ;
bis.close() ;
}
catch(Exception e)
{ }
}
}
public class DataRecordStoreTest extends MIDlet implements ItemStateListener
{
private Display display;
public DataRecordStoreTest()
{
display = Display.getDisplay(this);
}
public void startApp()
{
String dbname = "testdb" ;
Form f = new Form("RS Test") ;
RecordStore rs = openRSAnyway(dbname) ;
if( rs == null )
{
f.append("Table open fail") ;
}
else
{
try
{
FriendData fd = new FriendData() ;
fd.name = "李小明" ;
fd.tel = "62759933" ;
fd.sex = false ;
fd.age = 17 ;
byte tmp[] = fd.encode() ;
int id = rs.addRecord(tmp,0,tmp.length) ;
FriendData fd2 = new FriendData() ;
fd2.decode(rs.getRecord(id)) ;
f.append("姓名:"+ fd2.name) ;
f.append("\n 电話:"+ fd2.tel) ;
if(fd2.sex)
{
f.append("\n 性別: 男") ;
}
else
{
f.append("\n 性別: 女") ;
}
f.append("\n 年龄:"+ fd2.age) ;
rs.closeRecordStore() ;
deleteRS(dbname) ;
}
catch(Exception e){}
display.setCurrent(f) ;
}
}
public void pauseApp()
{ }
public void destroyApp(boolean unconditional)
{ }
public void itemStateChanged(Item item)
{ }
public RecordStore openRSAnyway(String rsname)
{
RecordStore rs = null ;
if(rsname.length() > 32)
return null ;
try
{
rs = RecordStore.openRecordStore(rsname,true) ;
return rs ;
}
catch(Exception e)
{
return null ;
}
}
public boolean deleteRS(String rsname)
{
if(rsname.length() > 32)
return false ;
try
{
RecordStore.deleteRecordStore(rsname) ;
}
catch(Exception e)
{
return false ;
}
return true ;
}
}