persistence

12
Mobile Application Development Persistence Institute for Mobile and Distributed Systems 1 Ch. Denzler J2ME Persistence Record Management System & File System Christoph Denzler University of Applied Studies Institute for Mobile and Distributed Systems J2ME Persistence IMVS, Ch. Denzler 2 Lernziele Sie verstehen wie mit MIDP Daten persistent gespeichert werden können können die persistente Datenhaltung für ein MIDlet selbst planen und implementieren können den persistenten Speicher nutzen um den beschränkten Hauptspeicher zu entlasten

Upload: miguel-angel-hernandez

Post on 14-Nov-2015

213 views

Category:

Documents


0 download

TRANSCRIPT

  • Mobile Application Development Persistence

    Institute for Mobile and Distributed Systems 1Ch. Denzler

    J2ME Persistence

    Record Management System & File SystemChristoph DenzlerUniversity of Applied StudiesInstitute for Mobile and Distributed Systems

    J2ME Persistence IMVS, Ch. Denzler 2

    Lernziele

    Sie verstehen wie mit MIDP Daten persistent

    gespeichert werden knnen knnen die persistente Datenhaltung fr ein

    MIDlet selbst planen und implementieren knnen den persistenten Speicher nutzen um

    den beschrnkten Hauptspeicher zu entlasten

  • Mobile Application Development Persistence

    Institute for Mobile and Distributed Systems 2Ch. Denzler

    J2ME Persistence IMVS, Ch. Denzler 3

    Inhalt

    CRUD Operationen Enumerationen Filter Comparatoren

    Types of memory (seen from J2ME perspective)

    J2ME Persistence IMVS, Ch. Denzler 4

    SmartPhone Memory

    1024 kB

    RAM10 RecordStores

    File System (optional JSR 75)

    MemoryCard(s)

    File System (optional JSR 75)

  • Mobile Application Development Persistence

    Institute for Mobile and Distributed Systems 3Ch. Denzler

    J2ME Persistence IMVS, Ch. Denzler 5

    Record Management System (RMS)

    Record Store accessed by name (unique per MIDlet suite) persistent across multiple invocations of a MIDlet only accessible by the MIDlets of the MIDlet suite

    which created the store contains collection of records Operations are

    atomic synchronized processed serially

    no SQL, no relational database management system

    J2ME Persistence IMVS, Ch. Denzler 6

    Record Management System (RMS)

    Records identified by a record identifier (int) plain array of bytes: byte[] when accessing it is the MIDlets responsibility to

    ensure the following: No thread may read a record that is concurrently changed or

    deleted by another thread No thread may delete a record that is concurrently read or

    changed by another thread No thread may change a record that is concurrently

    changed, read or deleted by another threat synchronize with RecordStore object!

  • Mobile Application Development Persistence

    Institute for Mobile and Distributed Systems 4Ch. Denzler

    Example

    J2ME Persistence IMVS, Ch. Denzler 7

    RecordStoreCollectionEnumeration

    null

    1

    2

    12

    24

    781

    nextRecord()

    nextRecord()

    Record Number

    byte[]

    J2ME Persistence IMVS, Ch. Denzler 8

    Manipulating Record Stores

    Managing RecordStore RecordStore openRecordStore(String name, boolean

    createIfNecessary) String[] listRecordStores() void deleteRecordStore(String name) closeRecordStore

    Handling Records int addRecord(byte[] data, int offset, int len) void setRecord(int id, byte[] data, int offset, int

    len) void deleteRecord(int id) byte[] getRecord(int id) int getNumRecords() int getNextRecordID()

    sta

    tic

  • Mobile Application Development Persistence

    Institute for Mobile and Distributed Systems 5Ch. Denzler

    Code example (writing a record)

    public int write(RecordStore rs)throws IOException, RecordStoreException { ByteArrayOutputStream baos =

    new ByteArrayOutputStream();DataOutputStream dos = new DataOutputStream(baos);writeImage(dos, pict);dos.writeUTF(text); dos.writeLong(date.getTime());// extract byte arraybyte[] data= baos.toByteArray();dos.close();// write record and return new record numberreturn rs.addRecord(data,0,data.length);

    }J2ME Persistence IMVS, Ch. Denzler 9

    Code example (cont.)

    void writeImage(DataOutputStream dos, Image img) {int w = img.getWidth(); // image sizeint h = img.getHeight(); int[] rgbi = new int[w*h];img.getRGB(rgbi,0,w,0,0,w,h); //img as int-array

    dos.writeInt(w);dos.writeInt(h);for(int i = 0; i < rgbi.length; ++i) {dos.writeInt(rgbi[i]); //write pixels image

    }}

    J2ME Persistence IMVS, Ch. Denzler 10

  • Mobile Application Development Persistence

    Institute for Mobile and Distributed Systems 6Ch. Denzler

    Code example (reading record)

    public void set(byte[] record){ByteArrayInputStream bais =

    new ByteArrayInputStream(record);DataInputStream dis = new DataInputStream(bais);try {

    pict = readImage(dis);text = dis.readUTF();long millis = dis.readLong();date = new Date(millis);dis.close();

    } catch(IOException e){ date = null;

    }}

    J2ME Persistence IMVS, Ch. Denzler 11

    Code example (cont.)

    private Image readImage(DataInputStream dis)throws IOException {int w = dis.readInt();int h = dis.readInt();int[] rgbi = new int[w*h];

    for(int i = 0; i < rgbi.length; ++i) {rgbi[i] = dis.readInt();

    }return Image.createRGBImage(rgbi, w, h, true);

    }

    J2ME Persistence IMVS, Ch. Denzler 12

  • Mobile Application Development Persistence

    Institute for Mobile and Distributed Systems 7Ch. Denzler

    Enumeration 1

    Similar to Iterator in Collection Framework Create enumeration withRecordEnumeration enumerateRecords(

    RecordFilter filter, // may be nullRecordComparator comparator, // may be nullboolean keepUpdated);

    use keepUpdated with caution! It sychronizeschanges in the records with the enumeration often better: use rebuild() on enumeration delete or insert invalidates enumeration update may put record out of sort order

    J2ME Persistence IMVS, Ch. Denzler 13

    Enumeration 2

    Reuse objects instead of creating new ones:RecordEnumeration re =rs.enumerateRecords(null, null, false);

    D d = new D(); //empty objectwhile(re.hasNextElement()) {byte[] record = re.nextRecord();d.set(record); // set fields of object

    } do not:while(re.hasNextElement())D d = new D(re.nextRecord());

    J2ME Persistence IMVS, Ch. Denzler 14

  • Mobile Application Development Persistence

    Institute for Mobile and Distributed Systems 8Ch. Denzler

    Comparator

    Used to determine the order of an enumeration Caution: performance consuming! int compare(byte[] rec1, byte[] rec2)

    returns -1 if rec1 < rec2: rec1 PRECEDES rec2 1 if rec1 > rec2: rec1 FOLLOWS rec2 0 if rec1 = rec2: rec1 is EQUIVALENT to rec2 in terms of sort order.

    J2ME Persistence IMVS, Ch. Denzler 15

    Filter

    Used to skip records during enumeration Only records matching filter criterion will be

    visited during enumeration boolean matches(byte[] candidate)

    Returns true if the candidate matches the implemented criterion.

    J2ME Persistence IMVS, Ch. Denzler 16

  • Mobile Application Development Persistence

    Institute for Mobile and Distributed Systems 9Ch. Denzler

    RecordListener

    Be informed about changes in a record store

    void recordAdded(RecordStore store, int recordId)void recordChanged(RecordStore store, int recordId)void recordDeleted(RecordStore store, int recordId)

    J2ME Persistence IMVS, Ch. Denzler 17

    File System

    The existence of a file system is optional. The file system API is part of JSR75 File systems can be mounted and unmounted

    (memory cards!) File systems support directories and files

    J2ME Persistence IMVS, Ch. Denzler 18

  • Mobile Application Development Persistence

    Institute for Mobile and Distributed Systems 10Ch. Denzler

    Support for File System available?

    Before use, check if file system is available:

    String version = System.getProperty( "microedition.io.file.FileConnection.version");

    version either contains the version of the API or null if JSR75 is not supported on the device

    J2ME Persistence IMVS, Ch. Denzler 19

    File System Roots

    get roots of file systemEnumeration roots =FileSystemRegistry.listRoots();

    while(roots.hasMoreElements()) {form.append((String)roots.nextElement() + "\n");

    }

    J2ME Persistence IMVS, Ch. Denzler 20

  • Mobile Application Development Persistence

    Institute for Mobile and Distributed Systems 11Ch. Denzler

    List Directory Content

    String root = ... // get name of file systemFileConnection fc = null;try {fc = (FileConnection)Connector.open("file:///" + root);Enumeration files = fc.list();while(files.hasMoreElements()) {

    form.append((String)files.nextElement() + "\n");}

    } catch(Exception e){form.append(root + " - no content to show! " +

    "reason: " + e.toString() + "\n");}

    J2ME Persistence IMVS, Ch. Denzler 21

    Read text file

    FileConnection fi = null;InputStream is = null;String dir = ... //define directory name hereString file = ... //define file name heretry {fc = (FileConnection)Connector.open("file:///" + dir + file,

    Connector.READ); if (fc.exists()) {

    is = fc.openInputStream();StringBuffer sb = new StringBuffer();int i;while ((i = is.read()) != -1) sb.append((char)i); // do something meaningful with sb

    } } catch(Exception e) { /* handle exception */ } 22J2ME Persistence IMVS, Ch. Denzler

  • Mobile Application Development Persistence

    Institute for Mobile and Distributed Systems 12Ch. Denzler

    J2ME Persistence IMVS, Ch. Denzler 23

    Resources

    JSR75:http://java.sun.com/javame/technology/msa/jsr75.jsp

    Getting Started with the FileConnection APIshttp://developers.sun.com/mobility/apis/articles/fileconnection/index.html