I'm developing a j2me application based on codenameone. I implements some codes and Now I wanna add database to my application. After search a lot I found Storage class of codenameone that simplify database concept in mobile application.
In this appliaction I create a class for each entity (like person, city, ...) and add "read" and "write" method to read and write data.
Some entity classes have 2 or more fields. So I must save and read them with Storage class.
How can I do this?
Here is my sample code:
package com.x.database;
import com.codename1.io.Storage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Iterator;
public class Person {
public Person(){
}
public Person(int pID, String pPersonNumber){
ID = pID;
PersonNumber = pPersonNumber;
}
public static String PERSON = "Person";
private Storage store;
private int ID;
public int getID(){
return ID;
}
public void setID(int pID){
ID = pID;
}
private String PersonNumber;
public String getPersonNumber(){
return PersonNumber;
}
public void setPersonNumber(String pPersonNumber){
PersonNumber = pPersonNumber;
}
public int getLastKeyNumber(){
if(store == null) {
store = Storage.getInstance();
}
Hashtable depHash = (Hashtable)store.readObject(PERSON);
ArrayList<String> keyArray = (ArrayList<String>)depHash.keys();
int i = 0;
for (Iterator<String> it = keyArray.iterator(); it.hasNext();) {
int tmp = Integer.parseInt(it.next());
i = i < tmp ? tmp : i;
}
return i;
}
public void write(Person pPerson){
if(store == null) {
store = Storage.getInstance();
}
if(!store.exists(PERSON)) {
Hashtable depHash = new Hashtable();
try {
depHash.put("0", pPerson);
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
store.writeObject(PERSON, depHash);
}
else {
Hashtable depHash = (Hashtable)store.readObject(PERSON);
ArrayList<Person> depArray = (ArrayList<Person>)depHash.keys();
for (Iterator<Person> it = depArray.iterator(); it.hasNext();) {
Person tmp = it.next();
if(!tmp.getPersonNumber().equals(pPerson)) {
depHash.put(String.valueOf(getLastKeyNumber()), pPerson.getPersonNumber());
store.writeObject(Person depHash);
}
}
}
}
public ArrayList<Person> readAll(){
Storage store = Storage.getInstance();
if(!store.exists(PERSON)) {
Hashtable depHash = (Hashtable)store.readObject(PERSON);
return (ArrayList<Person>)depHash.elements();
}
return new ArrayList<Person>();
}
}
In this code I have an error on write and read object on Storage.
How can I write one object in Storage and read it again?
Thanks in advance.