Bruce Scharlau, University of Aberdeen, 2010 Java ME Record Management System Mobile Computing.

Slides:



Advertisements
Similar presentations
Chapter 22 Implementing lists: linked implementations.
Advertisements

Chapter 23 Organizing list implementations. This chapter discusses n The notion of an iterator. n The standard Java library interface Collection, and.
Why not just use Arrays? Java ArrayLists.
11 Copyright © 2005, Oracle. All rights reserved. Using Arrays and Collections.
Bruce Scharlau, University of Aberdeen, 2012 Data storage options for mobiles Mobile Computing.
Connecting to Databases. relational databases tables and relations accessed using SQL database -specific functionality –transaction processing commit.
MIDP Mobile Information Device Profile Johnny Yau CIS 642 Prof. Insup Lee.
AITI Lecture 19 Linked List Adapted from MIT Course 1.00 Spring 2003 Lecture 26 and Tutorial Note 9 (Teachers: Please do not erase the above note)
COSC 1P03 Data Structures and Abstraction 10.1 The List If A is success in life, then A equals x plus y plus z. Work is x; y is play; and z is keeping.
Lists Chapter 4 Carrano, Data Structures and Abstractions with Java, Second Edition, (c) 2007 Pearson Education, Inc. All rights reserved X.
CMSC 132: Object-Oriented Programming II Nelson Padua-Perez William Pugh Department of Computer Science University of Maryland, College Park.
J2ME Melih Sakarya Java Teknolojileri Derneği. JVM JAVA Kullanılan yerler  Windows-Linux-Unix-Solaris  PDA lar  Smart Cardlar  Cep Telefonları  Appletler.
Java ME persistence made easy! by Thiago Rossato Thiago Moreira.
The Package Statement Group related interfaces and classes together Purpose: encapsulation and reduces name conflicts –private package classes not visible.
Socket Programming ENTERPRISE JAVA. 2 Content  Sockets  Streams  Threads  Readings.
Java File I/O. File I/O is important! Being able to write and read from files is necessary and is also one common practice of a programmer. Examples include.
BA1 RMS - Record Management System BA2 Record Store En Record er et bytearray af vilkårlig størrelse En RecordStore er et antal.
Core Java Lecture 4-5. What We Will Cover Today What Are Methods Scope and Life Time of Variables Command Line Arguments Use of static keyword in Java.
Java Programming Strings Chapter 7.
Composition CMSC 202. Code Reuse Effective software development relies on reusing existing code. Code reuse must be more than just copying code and changing.
Chapter 10 Introduction to Arrays
Chapter 51 Scripting With JSP Elements JavaServer Pages By Xue Bai.
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.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
1 CMSC 132: Object-Oriented Programming II Nelson Padua-Perez William Pugh Department of Computer Science University of Maryland, College Park.
Arrays, Loops weeks 4-6 (change from syllabus for week 6) Chapter 4.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L08 (Chapter 18) Binary I/O.
Persistent Storage  Record Stores  mini databases – represent data as byte records  Record Management System (RMS) API  Files and Directories  FileConnection.
1 CMSC 132: Object-Oriented Programming II Java Constructs Department of Computer Science University of Maryland, College Park.
Web Proxy Server. Proxy Server Introduction Returns status and error messages. Handles http CGI requests. –For more information about CGI please refer.
11 Values and References Chapter Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables.
1 Java Database Connection (JDBC) There are many industrial-strength DBMS's commercially available in the market. Oracle, DB2, and Sybase are just a few.
CSCI 6962: Server-side Design and Programming JDBC Database Programming.
Database Programming in Java Corresponds with Chapter 32, 33.
Mobile Applications with Java ME & BlackBerry. Overview Java ME –Networking –Databases Java ME and the BlackBerry –The BlackBerry wireless device –Converting.
LiveCycle Data Services Introduction Part 2. Part 2? This is the second in our series on LiveCycle Data Services. If you missed our first presentation,
Goals for Today  implement a Deck of Cards  composition  Iterator interface  Iterable interface 1.
Chapter 9 1 Chapter 9 – Part 1 l Overview of Streams and File I/O l Text File I/O l Binary File I/O l File Objects and File Names Streams and File I/O.
Arrays Part 9 dbg. Arrays An array is a fixed number of contiguous memory locations, all containing data of the same type, identified by one variable.
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.
JDBC. JDBC stands for Java Data Base Connectivity. JDBC is different from ODBC in that – JDBC is written in Java (hence is platform independent, object.
Android Storage. There are several options for storage of data with Android We can put data into a preferences file. We can put data into a ‘normal’ file.
Enterprise JavaBeans Understanding EJB Components Version 0.1 Kamal Wickramanayake
BlackBerry Persistent Storage Models Persistent Storage APIs and Record Management System.
1 Week 12 l Overview of Streams and File I/O l Text File I/O Streams and File I/O.
COP-3330: Object Oriented Programming Flow Control May 16, 2012 Eng. Hector M Lugo-Cordero, MS.
Grouping objects Collections and iterators Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Main.
(c) University of Washington15-1 CSC 143 Java List Implementation via Arrays Reading: 13.
HashCode() 1  if you override equals() you must override hashCode()  otherwise, the hashed containers won't work properly  recall that we did not override.
Fall 2002CS 150: Intro. to Computing1 Streams and File I/O (That is, Input/Output) OR How you read data from files and write data to files.
IBM TSpaces Lab 2 Customizing tuples and fields. Summary Blocking commands Tuple Expiration Extending Tuples (The SubclassableTuple) Reading/writing user.
PROG Mobile Java Application Development PROG Mobile Java Application Development Data Storage, Continued.
MIDP Programming Networking. Chapter Objectives The CLDC Streams Model Generic Connection Framework (GCF) Supported Protocols Creating a Connection Review.
Project Scenario for OpX. High-level Overview In the Test GUI Controller, opXController, for the opX command there is conceptually a call to an appropriate.
CIS Intro to JAVA Lecture Notes Set July-05 GUI Programming –TextField Action Listeners, JEditorPane action listeners, HTML in a JEditorPane,
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington 2D arrays COMP 102 # T1.
1 Lecture 5 More Programming Constructs Instructors: Fu-Chiung Cheng ( 鄭福炯 ) Associate Professor Computer Science & Engineering Tatung Institute of Technology.
Database Programming With Java & JDBC Reading: DD Ch. 18, pp al/jdbc/index.html, or anything covering JDBC.
MIDP Database Programming Using RMS: Jingwu He Csc 3360.
Puzzle 2 1  what does the following program print? public class Puzzle02 { public static void main(String[] args) { final long MICROS_PER_DAY = 24 * 60.
CS 31 Discussion, Week 7 Faisal Alquaddoomi, Office Hours: BH 2432, W 4:30-6:30pm, F 12:30-1:30pm.
Chapter 9 Introduction to Arrays Fundamentals of Java.
By: Eliav Menachi.  On Android, all application data (including files) are private to that application  Android provides a standard way for an application.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
CS320 Web and Internet Programming Database Access with JDBC Chengyu Sun California State University, Los Angeles.
Information and Computer Sciences University of Hawaii, Manoa
Java- I/O, SMS etc N Amanquah.
Object Oriented Programming in java
CS3220 Web and Internet Programming Database Access with JDBC
CS3220 Web and Internet Programming Database Access with JDBC
Presentation transcript:

Bruce Scharlau, University of Aberdeen, 2010 Java ME Record Management System Mobile Computing

Bruce Scharlau, University of Aberdeen, 2010 Mobiles + (Tunnels | Hills) = Lost connection

Bruce Scharlau, University of Aberdeen, 2010 Only commercial databases for Java ME handsets No widely available databases for Java ME on CLDC There are some open source packages if youre using CDC – see information page

Bruce Scharlau, University of Aberdeen, 2010 A RecordStore is NOT a database A RecordStore is an array of bytes with MIDP 2.0 a RecordStore can be shared across MIDlet suites RecordStore names must be unique

Bruce Scharlau, University of Aberdeen, 2010 Set the MIDlet-Data-Size attribute when using RMS Any MIDlet suite that uses RMS should specify the minimum number of bytes of data storage it requires, by setting the MIDlet- Data-Size attribute, in both the JAR manifest and the application descriptor. If the MIDlet-Data-Size attribute is missing, the device assumes the MIDlet suite requires no space for data storage.

Bruce Scharlau, University of Aberdeen, 2010 RecordStore if LILO Im telling you, its last in, last out No transactions then. Hmm

Bruce Scharlau, University of Aberdeen, 2010 If multiple apps share an RMS you need to write the logic for this RMS operations are thread-safe, but threads must still coordinate the reading and writing of data to the same record store. This is especially important if your RecordStore is shared in a MIDlet suite.

Bruce Scharlau, University of Aberdeen, 2010 RecordStore uses ID not index 1Tom6789 2Jane3680 3Henry1472 1Tom6789 2Jane3680 3Henry1472 4Mary8547 1Tom6789 2Jane3680 3Henry1472 4Mary8547 1Tom6789 2Jane3680 3Henry3456 4Mary8547 5Sarah Start with three Remove Jane, add Mary Remove Tom Change data, add row

Bruce Scharlau, University of Aberdeen, 2010 recordID = 1 for first record Yes, but when its gone its gone Auto- increment, nice. And it always starts at 1

Bruce Scharlau, University of Aberdeen, 2010 RecordStore Methods All are static so can be called without instance Can acquire a list of all record stores with String[ ] listRecordStores() Create/open record store with RecordStore openRecordStore(myStore, true) boolean to create or not if doesnt exist Delete via void deleteRecordStore(myStore)

Bruce Scharlau, University of Aberdeen, 2010 Adding Items myRecords.addRecord(myBytes, 0, myBytes.length); byteArray of data to be written to the store Offset from which to start writing the data How much of byteArray should be written

Bruce Scharlau, University of Aberdeen, 2010 Modifying a Record Same as writing to a record, but must also pass in the recordID as the first parameter myRecords.addRecord(recordID, myBytes, 0, myBytes.length);

Bruce Scharlau, University of Aberdeen, 2010 Reading a record Either: –A) byte [ ] recordData = myRecords.getRecord(1) –B) byte[ ] myBuffer = new byte[BIG_ENOUGH]; int readRecord = myRecords.getRecord(1, myBuffer, 0); Instead of creating a new byte array to hold the result, this version uses one from the application

Bruce Scharlau, University of Aberdeen, 2010 Meta Information long lastModified() timestamp of store String getName() of the store int getNextRecordID() to be added to the store int getRecordSize(int myRecord) for the size of the specified record int getSize() of the complete store

Bruce Scharlau, University of Aberdeen, 2010 Custom Objects Problem – how to serialise objects and their attributes? Create class and then write variables to bytes and then store this object to the array Reverse the process to recreate the object

Bruce Scharlau, University of Aberdeen, 2010 Custom Object - class class AuctionItems { String descriptionAI; String summaryAI; String startPriceAI; long startDateAI; } Create class to hold variables for custom object, which can then be passed around as required

Bruce Scharlau, University of Aberdeen, 2010 Write Custom object private byte[] getBytes() throws IOException{ ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(baos); dos.writeUTF(descriptionAI); dos.writeUTF(summaryAI); dos.writeUTF(startPriceAI); dos.writeLong(startDateAI); dos.close(); baos.close(); return baos.toByteArray(); } * Variables from Form * Could also write out Int, Long, Short, and others * Variables from Form * Could also write out Int, Long, Short, and others

Bruce Scharlau, University of Aberdeen, 2010 Read Custom Object public AuctionJ2meItems(byte[] data) throws RecordStoreNotOpenException, InvalidRecordIDException, RecordStoreException, IOException { ByteArrayInputStream bais = new ByteArrayInputStream(data); DataInputStream dis = new DataInputStream(bais); this.descriptionAI = dis.readUTF(); this.summaryAI = dis.readUTF(); this.startPriceAI = dis.readUTF(); this.startDateAI = dis.readLong(); } A read from the store is the constructor for object and gets used like this: byte[] inputData = auctionItems.getRecord(item); AuctionItems ai = new AuctionItems(inputData); item is an int

Bruce Scharlau, University of Aberdeen, 2010 Could write your own implementation to make RMS work like JDBC To make working with RMS like using JDBC, and Java objects, need to write structure to handle this

Bruce Scharlau, University of Aberdeen, 2010 Use either brute force or enumeration to traverse a RecordStore Because record IDs are fixed, they are not continuous. A deleted record ID is not filled by an incoming record, so iteration doesnt work. RecordStore is NOT a database as shown by this operation

Bruce Scharlau, University of Aberdeen, 2010 Fetch records one by one in a simple way... RecordStore rs =... // an open record store int lastID = rs.getNextRecordID(); int numRecords = rs.getNumRecords(); int count = 0; for( int id = 1; id < lastID && count < numRecords; ++id ){ try { byte[] data = rs.getRecord( id );... // process the data ++count; } catch( InvalidRecordIDException e ){ // just ignore and move to the next record } catch( RecordStoreException e ){ // a more general error that should be handled // somehow break; }...

Bruce Scharlau, University of Aberdeen, 2010 You can also use RecordEnumeration RecordStore rs =... // an open record store RecordEnumeration enum = rs.enumerateRecords( null, null, false ); try { while( enum.hasNextElement() ){ int id = enum.nextRecordId(); byte[] data = rs.getRecord( id );... // do something here } } catch( RecordStoreException e ){ // handle the error here }...

Bruce Scharlau, University of Aberdeen, 2010 Sorting Objects Use RecordEnumerations to sort through records using compare() –Returns either: EQUIVALENT, FOLLOWS or PRECEDES Can also use enumerateRecords() with its RecordFilter to sift through recordStore

Bruce Scharlau, University of Aberdeen, 2010 Use RecordComparator to sort records for display import javax.microedition.rms.*; import java.lang.*; public class MyComparator implements RecordComparator { public int compare(byte rec1[], byte rec2[]) { String recstr1 = new String(rec1); String recstr2 = new String(rec2); int num = recstr1.compareTo(recstr2); if (num != 0) { return ( num < 0 ? RecordComparator.PRECEDES : RecordComparator.FOLLOWS); } else { return RecordComparator.EQUIVALENT; }

Bruce Scharlau, University of Aberdeen, 2010 Dukes Auction MIDlet retrieves list of auction items AuctionMIDlet Servlet Database Send query to db AuctionItems ResultSet returned Vector returned AuctionJ2meItems Creates vector of these Serialises to RMS

Bruce Scharlau, University of Aberdeen, 2010 Call the servlet with byte hc = (HttpConnection) Connector.open(url); baos = new ByteArrayOutputStream(); dos = new DataOutputStream(baos); dos = hc.openDataOutputStream(); dos.writeByte(OPERATION_LIST_ALL_ITEMS); dos.close(); Use DataInput/ OutputStreams and ByteArrayOutputStream to manage data

Bruce Scharlau, University of Aberdeen, 2010 The servlet responds to the call private void j2me_selectItem(DataInputStream call, DataOutputStream result, String quantity) throws IOException, SQLException { AuctionItems auctionI = new AuctionItems(); Vector items = new Vector (); items = auctionI.getJ2meAuctionItems("all"); Iterator iter = items.iterator(); while (iter.hasNext()) { AuctionJ2meItems aItem = new AuctionJ2meItems(); aItem = (AuctionJ2meItems) iter.next(); result.writeUTF("next"); result.writeUTF(aItem.descriptionAI); result.writeUTF(aItem.summaryAI); result.writeUTF(aItem.startPriceAI); result.writeLong(aItem.startDateAI); } return; } Use AuctionItems and AuctionJ2meItems Write stream to MIDlet

Bruce Scharlau, University of Aberdeen, 2010 MIDlet captures stream and writes object to RMS inputStream = hc.openDataInputStream(); int contentLength = (int) hc.getLength(); String k = ""; inputStream.skipBytes(4); while (inputStream.available() > 0) { k = inputStream.readUTF(); if (k.equals("next")) { aItem = new AuctionJ2meItems(inputStream.readUTF(), inputStream.readUTF(), inputStream.readLong()); ByteArrayOutputStream baos2 = new ByteArrayOutputStream(); DataOutputStream dos2 = new DataOutputStream(baos2); aItem.serialize(dos2); byte[] b = baos2.toByteArray(); try { auctionItemStore.addRecord(b, 0, b.length); } catch (Exception e) { // more code left out here

Bruce Scharlau, University of Aberdeen, 2010 Then we can read the RecordStore into a form with read(1); private void read(int item) throws RecordStoreNotOpenException, InvalidRecordIDException, RecordStoreException, IOException { byte[] inputData = auctionItemStore.getRecord(item); AuctionJ2meItems ai = new AuctionJ2meItems(inputData); ai.print(); // set up form … readForm.append(description); readForm.append(summary); readForm.append(startPrice); readForm.append(startDate); description.setString(ai.descriptionAI); summary.setString(ai.summaryAI); startPrice.setString(ai.startPriceAI); startDate.setString(String.valueOf(new java.util.Date(ai.startDateAI))); // add commnds to form … readForm.setCommandListener(this); display.setCurrent(readForm); } Notice that we convert startDataAI to Date from long Use AuctionJ2meItem object

Bruce Scharlau, University of Aberdeen, 2010 Navigate through records with previous and next commands } else if (c == mPrevCommand) { try { if (currentId == 1) { Alert alertPrev = new Alert("No previous records"); alertPrev.setTimeout(Alert.FOREVER); alertPrev.addCommand(mReadAuctionCommand); alertPrev.setCommandListener(this); display.setCurrent(alertPrev); } else { currentId--; read(currentId); } catch (RecordStoreNotOpenException e) { // pl;us other exceptions … } else if (c == mNextCommand) { try { currentId++; read(currentId); … Check for no record, and keep track of recordID

Bruce Scharlau, University of Aberdeen, 2010 Using AuctionJ2meItem on server and handset causes issues Closely couples the code between the two Explore alternatives before coupling code May be able to use interoperable option

Bruce Scharlau, University of Aberdeen, 2010 The more classes in the app the more memory it consumes Each class in the app will need to be loaded All classes in MIDP are loaded dynamically at the start during class verification Keeping classes small, and to a minimum is therefore important in mobile Java

Bruce Scharlau, University of Aberdeen, 2010 Summary RMS is similar to database, with significant differences that you need to accommodate Map the bytes to objects for convenience Sometimes need to share code across platforms (server and Java ME client) to ease programming