BlackBerry Persistent Storage Models Persistent Storage APIs and Record Management System.

Slides:



Advertisements
Similar presentations
Chapter 23 Organizing list implementations. This chapter discusses n The notion of an iterator. n The standard Java library interface Collection, and.
Advertisements

11 Copyright © 2005, Oracle. All rights reserved. Using Arrays and Collections.
Bruce Scharlau, University of Aberdeen, 2010 Java ME Record Management System Mobile Computing.
Bruce Scharlau, University of Aberdeen, 2012 Data storage options for mobiles Mobile Computing.
Transparency No. 1 Java Collection API : Built-in Data Structures for Java.
Java Card Technology Ch04: Java Card Object
MIDP Mobile Information Device Profile Johnny Yau CIS 642 Prof. Insup Lee.
Java ME persistence made easy! by Thiago Rossato Thiago Moreira.
BA1 RMS - Record Management System BA2 Record Store En Record er et bytearray af vilkårlig størrelse En RecordStore er et antal.
Problem Solving 5 Using Java API for Searching and Sorting Applications ICS-201 Introduction to Computing II Semester 071.
Chapter 7 Strings F To process strings using the String class, the StringBuffer class, and the StringTokenizer class. F To use the String class to process.
Java Card Technology Ch07: Applet Instructors: Fu-Chiung Cheng ( 鄭福炯 ) Associate Professor Computer Science & Engineering Computer Science & Engineering.
Hashing as a Dictionary Implementation
Appendix I Hashing. Chapter Scope Hashing, conceptually Using hashes to solve problems Hash implementations Java Foundations, 3rd Edition, Lewis/DePasquale/Chase21.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by.
Hashing Chapters What is Hashing? A technique that determines an index or location for storage of an item in a data structure The hash function.
Cosc 4730 Blackberry: Record Store & SQLite. Introduction RecordStore – Comes from JavaME, MIDP 1.0 On some phone who where you may not have a filesystem.
VBA Modules, Functions, Variables, and Constants
1 L43 Collections (3). 2 OBJECTIVES  To use the collections framework interfaces to program with collections polymorphically.  To use iterators to “walk.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L16 (Chapter 22) Java Collections.
J.43 ARRAYS  A Java array is an Object that holds an ordered collection of elements.  Components of an array can be primitive types or may reference.
1 Java Object Model Part 1. 2 Type Definition: set of values – a set of values and set of operations –a set of operations that can be applied to those.
© 2009 Research In Motion Limited Data structures and memory management on mobile devices.
CHAPTER 6 Stacks Array Implementation. 2 Stacks A stack is a linear collection whose elements are added and removed from one end The last element to be.
Introducing Hashing Chapter 21 Copyright ©2012 by Pearson Education, Inc. All rights reserved.
Persistent Storage  Record Stores  mini databases – represent data as byte records  Record Management System (RMS) API  Files and Directories  FileConnection.
Detecting Changes  ItemStateListener interface – detect changes in internal state of an Item  new selection made in a ChoiceGroup  adjusted value of.
Data Storage: Part 1 (Preferences)
Databases for Mobile Devices Introduction. Overview Different types of data storages Memory management Local database techniques.
Classes, Objects, Arrays, Collections and Autoboxing Dr. Andrew Wallace PhD BEng(hons) EurIng
Abstract Data Types (ADTs) and data structures: terminology and definitions A type is a collection of values. For example, the boolean type consists of.
Mobile Applications with Java ME & BlackBerry. Overview Java ME –Networking –Databases Java ME and the BlackBerry –The BlackBerry wireless device –Converting.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 22 Java Collections.
Collections F The limitations of arrays F Java Collection Framework hierarchy  Use the Iterator interface to traverse a collection  Set interface, HashSet,
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 22 Java Collections.
Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Generalized Containers CSIS 3701: Advanced Object Oriented Programming.
GENERIC COLLECTIONS. Type-Wrapper Classes  Each primitive type has a corresponding type- wrapper class (in package java.lang).  These classes are called.
PROG Mobile Java Application Development PROG Mobile Java Application Development Memory and Memory Issues Data Storage.
Chapter 4. INTERNAL REPRESENTATION OF FILES
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Arrays BCIS 3680 Enterprise Programming. Overview 2  Array terminology  Creating arrays  Declaring and instantiating an array  Assigning value to.
SQLite Supported by BlackBerry OS 5.0 Using SQLite.
Copyright © 2002, Systems and Computer Engineering, Carleton University Hashtable.ppt * Object-Oriented Software Development Unit 8.
Chapter 18 Java Collections Framework
Slides prepared by Rose Williams, Binghamton University Chapter 5 Defining Classes II.
Introduction to Java Lecture Notes 3. Variables l A variable is a name for a location in memory used to hold a value. In Java data declaration is identical.
Hashing as a Dictionary Implementation Chapter 19.
모바일 자바 프로그래밍 MIDP RMS Ps lab 오민경. MIDP RMS  RMS (Record Management System)  MIDP 에서 정의하는 영속성을 지닌 자체 데이터 저장 공간  Record Store 의 집합으로 구성된 아주 간단한 데이터베이스.
Building Java Programs Bonus Slides Hashing. 2 Recall: ADTs (11.1) abstract data type (ADT): A specification of a collection of data and the operations.
U n i v e r s i t y o f H a i l 1 ICS 202  2011 spring  Data Structures and Algorithms 
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
CMSC 202 Containers and Iterators. Container Definition A “container” is a data structure whose purpose is to hold objects. Most languages support several.
MIDP Database Programming Using RMS: Jingwu He Csc 3360.
Collections Dwight Deugo Nesa Matic
CHAPTER 9 File Storage Shared Preferences SQLite.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by.
Coming up Implementation vs. Interface The Truth about variables Comparing strings HashMaps.
By: Eliav Menachi.  On Android, all application data (including files) are private to that application  Android provides a standard way for an application.
Phonegap Bridge – Storage CIS 136 Building Mobile Apps 1.
The Record Store ( ) Frank Ducrest. The Record Store 2 The Record Store provides persistence of data between MIDlet runs not quite a DBMS API.
The Methods and What You Need to Know for the AP Exam
Java- I/O, SMS etc N Amanquah.
EECE 310: Software Engineering
Java Primer 1: Types, Classes and Operators
CIS 136 Building Mobile Apps
Chapter 7: Strings and Characters
null, true, and false are also reserved.
Object Oriented Programming in java
Presentation transcript:

BlackBerry Persistent Storage Models Persistent Storage APIs and Record Management System

Overview Part 1- –Persistent Storage APIs Part 2- –MIDP Record Store (RMS)

PART 1 – PERSISTENT STORAGE APIS

PersistentStore class PersistentStore provides a means for storing persistent objects The class to work with persistent store is net.rim.device.api.system.PersistentStore Persistent objects consisting of a key-value pair, are committed to the persistent store. You can retrieve them from the persistent store by their key.

PersistentStore class (Cont.) To retrieve them, invoke PersistentStore.getPersistentObject(long key) method. Example: // Hash of cmer.project.persistentobject.uniquekey long KEY = 0x5602c4fba32d702L ; static PersistentObject store; Static{ store = PersistentStore.getPersistentObject( KEY ); }

PersistentStore class (Cont.) In the previous example, using a static constructor means that the PersistentObject is created only once. The key is a hash of a string. The string is typically the name of your package.

Persistent Objects Persistent Objects are objects whose content remains persistent between device resets. There are two types of persistent objects: –PersistentObject –Implicit persistence Persistent objects are stored permanently in a PersistentStore object.

Implicit persistence A custom data types are implicitly persistable if they implement a Persistable interface. These data types are: –Boolean -Vector –Byte- Hashtable –Integer- Object –Long- Short –String

Example- Implicit Persistence private static final class Employee implements Persistable { private String name; private String address; public Employee() { } public String getName() { return this.name; } public void setName(String value) { this.name = value; } …… }

PersistentObject Class The class to work with Persistent Object is net.rim.device.api.system.PersistentObject Persistent objects are stored in a PersistentStore object. When a persistent object is stored to persistent store, the persistent object is stored in flash memory.

PersistentObject class (Cont.) A persistent Object consists of a key-value pair. Each PersistentObject has a unique long key. The unique key acts as an identifier for an object meaning that objects can be retrieved from a PersistentStore via this key.

PersistentObject class (Cont.) In BlackBerry JDE, you are able to build a unique key. You can do it by writing a string in IDE (any string) such as “cmer.project.persistentobject.uniquekey” Then, Right-click this string and select “convert to long”

PersistentObject class (Cont.)

PersistentObject class (Cont.) You can get and set the contents of the object using these methods: –void setContents( Object contents) –Object getContents() When you set the content of the object, you may want to store the object in the persistent store. This is done by invoking commit(). Commit() method writes the contents of the persistent object to flash memory (persistent memory)

Steps for Storing Data in Persistent Store 1.Create a unique key 2.Retrieve a persistentObject from the persistent store by the key 3.Create, change or update the object’s value. The object can be any data type such as String, int, String[], … 4.Set the contents of the persistentObject to the object you have in step 3 5.Commit the persistentObject to the Persistent Store

Example- Create a Persistent Object static { //Create a long key – Key: CMER.lab1.persistentAPI long dbkey = 0x6b5fddcbb010cf0cL; store = PersistentStore.getPersistentObject(dbkey); synchronized (store) { if (store.getContents() == null) { store.setContents(new Vector()); store.commit(); } table = new Vector(); table = (Vector) store.getContents(); }

Example- Store a Persistent Object private static Vector table; private static PersistentObject store; …… private MenuItem _save = new MenuItem("Save", 110, 10) { public void run() { table.addElement(favor); synchronized (store) { store.setContents(table); store.commit(); }

Example- Retrieve a Persistent Object private static Vector table; private static PersistentObject store; …… private MenuItem _retrieve = new MenuItem("Retrieve", 110, 11) { public void run() { synchronized (store) { table = (Vector) store.getContents(); } };

Transactions in Persistent Storage Model There are two common ways to commit objects to the persistent store: –Single transaction –Batches of transactions In single transaction, commit() and forceCommit() are used to commit a single object to the persistent store.

Transactions in Persistent Storage Model (Cont.) These two methods do the same thing. However, forceCommit() commits the object immediately to the persistent store. Example: synchronized (store) { store.setContents(table); store.commit(); }

Batches of Transaction A batch transaction commits objects to the persistent store. To do this: –Invoke PersistentStore.getSyncObject() This method retrieves the persistent store monitor to lock the object. –Synchronize on the object –Invoke commit() as necessary.

Example- Batches of Transaction synchronized (PersistentStore.getSynchObject()) { ….. store.commit(); }

Delete a Database To delete a database, invoke –PersistentStore.destroyPersistentObject(long key) It removes the persistent object from the store by key. By deleting the PersistentObject, you permanently remove all persistent data that your application has stored.

PART 2 – RMS (RECORD MANAGEMENT SYSTEM)

Record Management System MIDP provides a mechanism for Midlets to persistently store data and retrieve it later to/from small device. This is called Record Management System (RMS) It is a Java ME package. However, BlackBerry devices support RMS. Although, it is limited in capabilities

RMS (Cont.) RMS library package is javax.microedition.rms A Record Store is a collection of persistent records Each Record Store has a unique name which is case-sensitive and between 1-32 unicode characters Record ID 0 Record ID 1 RecordStore

Record A Record is an array of Bytes Each record in a record store can have a different length and different types Each record has a unique identifier called recordID –It is used to retrieve a record from record store –It is assigned automatically by an increasing-by- one algorithm

Methods public static RecordStore openRecordStore( String recordStoreName, boolean createIfNecessary) throws RecordStoreException, RecordStoreFullException, RecordStoreNotFoundException Opens a record store and returns a RecordStore object. For any access to record store, you should call it first

Methods (Cont.) public String getName() throws RecordStoreNotOpenException Returns the name of the record store opened or created public int getNumRecords() throws RecordStoreNotOpenException Returns the number of records currently in the record store.

Methods (Cont.) public static void deleteRecordStore(String recordStoreName) throws RecordStoreException, RecordStoreNotFoundException Deletes the named record store. MIDlet suites are only allowed to delete their own record stores. A record must be closed before it can be deleted.

Methods (Cont.) public void closeRecordStore() throws RecordStoreNotOpenException, RecordStoreException This method is called when the MIDlet requests to close the record store. Note that the record store will be closed since closeRecordStore() is called as many times as openRecordStore() is called

Sharing Record Store Midlets within a MIDlet suit can share their record store. If multiple midlet within a MIDlet suit want to access a record store, the synchronization of the access operation must be implemented. In MIDP 2.0, Midlets whitin a midlet suit can access to the record stores of the other midlet suits on the device. In MIDP 1.0, this capability is not supported.

Sharing Record Store (Cont.) To share a record store, you should set options when you create a record store using openRecordStore( ) –authmod: it can be AUTHMODE_PRIVATE meaning that only midlet suit that created the record store can access to it OR AUTHMODE_ANY allows any midlet to access the record store –writable: also, you can identify the type of access whether it is read-only or it allows others to write to it.

Manipulating Records public int addRecord(byte[] data, int offset, int numBytes) throws RecordStoreNotOpenException, RecordStoreException, RecordStoreFullException Adds a new record to the record store. The recordID for this new record is returned. data - the data to be stored in this record. offset - the index into the data buffer of the first relevant byte for this record numBytes - the number of bytes of the data buffer used for this record (may be zero)

Manipulating Records (Cont.) public void deleteRecord(int recordId) throws RecordStoreNotOpenException, InvalidRecordIDException, RecordStoreException To delete a record from the record store public byte[] getRecord(int recordId) throws RecordStoreNotOpenException, InvalidRecordIDException, RecordStoreException Returns a record

Manipulating Records (Cont.) public int getRecord(int recordId, byte[] buffer, int offset) throws RecordStoreException, RecordStoreNotOpenException, InvalidRecordIDException, Returns the record in the given record store, recordId - the ID of the record to be retrieved buffer - the byte array in which to copy the data offset - the index into the buffer in which to start copying

Manipulating Records (Cont.) public void setRecord(int recordId, byte[] newData, int offset, int numBytes) throws RecordStoreNotOpenException, InvalidRecordIDException, RecordStoreException, RecordStoreFullException Override the record identified by recordId

Example- Open & Close a Record Store try{ // To open a record store RecordStore rs = RecordStore.openRecordStore(recordStore_name,true); …. //Close a record store rs.closeRecordStore(); }catch(Exception e) { System.err.println(e.toString()); }

Example- Add & Delete a Record byte[] rec = str.getBytes(); try { //Add a new record rs.addRecord(rec, 0, rec.length); …. //Delete a record rs.deleteRecord(recId); }catch (Exception e) { System.err.println(e.toString()); }

Example- Retrieve & Update a Record byte[] recData= null; try { //Retrieve a record from the record store recData = rs.getRecord(recId); String retrievedRecord = new String(recData); ….. //Update a record in the record store rs.setRecord(recordId, str.getBytes(), 0, str.length()); } catch (Exception e) { System.err.println(e.toString()); return null; }

Example- Delete a Record Store if (RecordStore.listRecordStores() != null) { try { //Delete a record store RecordStore.deleteRecordStore(recordStore_name); } catch (Exception e) { System.err.println(e.toString()); }

Filtering, Comparing, Listening and Enumerating Records RMS provides 4 Java interfaces used to filter, search and sort a record store: –RecordFilter Interface –RecordComparator Interface –RecordListener Interface –RecordEnumerator Interface

RecordFilter Interface Allows to define filter for searching records It has the following method: public boolean matches(byte[] record) Returns true if the candidate matches the user- defined search criteria. record - the record to consider.

Example- RecordFilter public class SearchFilter implements RecordFilter { private String searchText = null; public SearchFilter(String searchText) { this.searchText = searchText.toLowerCase(); // This is the text to search for } public boolean matches(byte[] candidate) { String str = new String(candidate).toLowerCase(); // Look for a match if (searchText != null && str.indexOf(searchText) != -1) return true; else return false; }

RecordComparator Interface It is used to compare two records to check if they match public int compare(byte[] rec1, byte[] rec2) rec1- the first record to use for comparison. rec2 - the second record to use for comparison. Return value: EQUIVALENT: two records are the same in terms of the search FOLLOWS: the first record follows the second record in terms of search or search order PRECEDES: the first record precedes the right record in terms of search or sort order.

Example- RecordComparator public class SortCompare implements RecordComparator { public int compare(byte[] rec1, byte[] rec2){ String str1 = new String(rec1); String str2 = new String(rec2); int result = str1.compareTo(str2); if (result == 0) return RecordComparator.EQUIVALENT; else if (result < 0) return RecordComparator.PRECEDES; else return RecordComparator.FOLLOWS; }

RecordListener Interface It is used to monitor the manipulating records such as add, delete, … –public void recordAdded(RecordStore recordStore, int recordId) it is called when a record is added to the record store –public void recordChanged(RecordStore recordStore, int recordId) it is called after a record in a record store has been changed.

RecordListener Interface (Cont.) –public void recordDeleted( RecordStore recordStore, int recordId) it is called after a record has been deleted from a record store. If the implementation of this method tries to retrieve the record from the record store, an InvalidRecordIDException will be thrown

Example- RecordListener public class Lab10RecordListner implements RecordListener{ public void recordAdded(RecordStore recordStore, int recordId) { try { System.out.println("Record with ID#: " + recordId + " added to RecordStore: " + recordStore.getName()); } catch (Exception e) { System.err.println(e); } } public void recordDeleted(RecordStore recordStore, int recordId) { try { System.out.println("Record with ID#: " + recordId + " deleted from RecordStore: " + recordStore.getName()); } catch (Exception e) { System.err.println(e); } } public void recordChanged(RecordStore recordStore, int recordId) {} }

RecordEnumerator Interface It provides a method to return an enumeration for traversing a set of records in the record store public RecordEnumeration enumerateRecords( RecordFilter filter, RecordComparator comparator, boolean keepUpdated) throws RecordStoreNotOpenException filter : - if non-null, it determines what subset of the record store records will be used Comparator: - if non-null, it will be used to determine the order in which the records are returned

RecordEnumerator Interface (Cont.) keepUpdated - if true, the enumerator will keep its enumeration current with any changes in the records of the record store. - If false the enumeration will not be kept current and may return recordIds for records that have been deleted or miss records that are added later.

Example- Sort Sort using Record Enumerator public void sortingReadRMS(){ try{ if (rs.getNumRecords() > 0){ SortCompare comp = new SortCompare(); RecordEnumeration re=rs.enumerateRecords(null, comp, false); list1.deleteAll(); while (re.hasNextElement()){ String str = new String(re.nextRecord()); list1.append(str, null); } } catch (Exception e) { System.err.println(e.toString()); }