If you want a list of 10 messages, I would use a Vector
for that. Vectors have an order to them, and they are Persistable (*). You can remove the first (oldest) element from the Vector, and add a new one to the end.
It looks like your persistent store keeps one main Hashtable
(which is good). Change your persistent model to be like this:
- Hashtable
- Vector (key = "chatMsgs")
- String
- String
- String
- String
- String
- String
- String
- String
- String
- String
So, maybe something like this:
public void saveChatMsg(String newMsg) {
Vector msgs = PersistentStoreHelper.persistentHashtable.get("chatMsgs");
// add the new msg (to the end of the vector)
msgs.addElement(newMsg);
// delete old messages, if the vector is full
while (msgs.size() > 10) {
msgs.removeElementAt(0);
}
// store the modified vector back to the persistent store
PersistentStoreHelper.persistentHashtable.put("chatMsgs", msgs);
// I'm assuming your PersistentStoreHelper calls commit() somewhere in here
}
/** @param index - 0 is the oldest, 9 is the newest */
public String getChatMsg(int index) {
Vector msgs = PersistentStoreHelper.persistentHashtable.get("chatMsgs");
return (String)msgs.elementAt(index);
}
Edit:
(*) the BlackBerry API doc I linked to, and the BlackBerry Java Storage APIs documentation, both list java.util.Vector
as a Persistable
class. So does this answer/comment. However, the actual API javadoc for Vector
does not say that it implements Persistable
. I'm not in a position to run the code right now, but if a Vector
of String
objects doesn't work for you, you could always use a subclass of Vector
, like ContentProtectedVector, that the API docs explicitly list as Persistable
. Post a comment if you wind up needing to do that, for others' benefit.