MobiCom on Android      XML DB Specifications, OOP DB Modeling,     Image Storage & Retrieval with SQLite DBs,       SQLit...
Outline   ●       XML DB Specs, Java Objects, and SQLite       Databases   ●       Image Storage & Retrieval with SQLite  ...
XML DB Specs, Java Objects, & SQLite              Databases                       source code is herehttp://www.youtube.co...
BOOK_TITLE Table                      Database Schema                      ID | Title | BookAuthor | Translator | ISBN | P...
BOOK_AUTHOR Table               Database Schema               ID | Name | BirthYear | DeathYear | Country               Da...
BOOK_COVER_IMAGE Table                        Database Schema                        ISBN | Image (BLOB)                  ...
Image Blobshttp://www.youtube.com/vkedco   www.vkedco.blogspot.com
BOOK_ORDER Table                    Database Schema                    ID|ISBN|FirstName|LastName|Price                   ...
Data Management Model        XML                           Java Objects           SQLite DB        GUIhttp://www.youtube.c...
XML ↔ Java                         XML                                                 Java    <string-array name="book_co...
Getting XML DB Specs      // Populate book cover images      public static String[] getXMLTableSpecs(Context cntxt, int ta...
Java Object Creation      private static BookCoverImage createBookCoverImageObject(Context cntxt,                         ...
Java Object DB Insertion      // Populate book cover images      String[] book_cover_image_table = getXMLTableSpecs(cntxt,...
Java Object DB Insertion      public long insertUniqueBookCoverImage(BookCoverImage bci) {          byte[] bitmapbytes = b...
DB Cursor Objects  ●      Cursor object is a result set of a query  ●      A result set can be thought of as a table where...
Cursor Manipulation Logic           // 1. Obtain Cursor object          Cursor crsr = db.query( query arguments);         ...
Image Store & Retrieval                        with                  SQLite Databaseshttp://www.youtube.com/vkedco   http:...
SQLite BLOB  ●      SQLite has the data type BLOB  ●      The BLOB data type allows for the persistence      and retrieval...
Image Storage Steps  ●      Get an image from a resource (local file, remote file,      URI, etc)  ●      Create a Bitmap ...
Summary of Coding Steps       Bitmap bmp = null;       Resources mRes = cntxt.getResources();       // 1. decode resource ...
SQLite Scripts & Triggershttp://www.youtube.com/vkedco   http://www.vkedco.blogspot.com
SQLite Triggers  ●      A trigger is an SQLite procedure (script) that      can be attached to specific events  ●      Typ...
Sample Table: my_math_tbl    ID   first_name   last_name   research_area    birth_year   dearth_year   time_stamp    1    ...
Sample Trigger Script: table_script          -- sample sqlite script for creating my_math_tbl          CREATE TABLE my_mat...
Trigger Activation  ●      The sample script table_script triggers on insertions and udpates a date      value in a newly ...
Stored SQLite Procedures                        source code is herehttp://www.youtube.com/vkedco   http://www.vkedco.blogs...
SQLite Stored Procedures  ●      A stored procedure is a piece of compute code      (written in specific programming langu...
Sample Table 01: Book Title    ID   Title                      Author               Translator           ISBN            P...
SQLiteDatabase.query()           SQLiteDatabase db;           Cursor crsr =             db.query(String table,      // tab...
sample_query_01: Part 01      String sample_query_01() {      Cursor rslt = mDb.query(BOOK_TITLE_TABLE, // table name     ...
sample_query_01: Part 02      if ( rslt.getCount() != 0 ) {        rslt.moveToFirst();        while ( rslt.isAfterLast() =...
Example: sample_query_02()    static final String SQL_QUERY_02 = "SELECT Name, BirthYear FROM book_author";    static fina...
sampel_query_03: Part 03             buffer.append("ID = " + id + "n");             buffer.append("TITLE = " + book_title ...
Example: sample_query_05()    static final String SQL_QUERY_05 =    "SELECT Title, Translator, Price FROM book_title WHERE...
Example: sample_query_06()    static final String SQL_QUERY_06 =    "SELECT ISBN, SUM(Price) FROM book_order GROUP BY ISBN...
Example: sample_query_07()    static final String SQL_QUERY_07 =    "SELECT LastName, SUM(Price) FROM book_order GROUP BY ...
References   ●       www.sqlite.org/datatype3.html   ●       http://developer.android.com/reference/android/database/sqlit...
Upcoming SlideShare
Loading in …5
×

MobiCom on Android: XML DB Specifications, OOP DB Modeling, Image Storage & Retrieval with SQLite DBs, SQLite Scripts & Triggers, Stored SQLite Procedures

818 views
740 views

Published on

MobiCom on Android: XML DB Specifications, OOP DB Modeling, Image Storage & Retrieval with SQLite DBs, SQLite Scripts & Triggers, Stored SQLite Procedures

Published in: Software
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
818
On SlideShare
0
From Embeds
0
Number of Embeds
395
Actions
Shares
0
Downloads
0
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

MobiCom on Android: XML DB Specifications, OOP DB Modeling, Image Storage & Retrieval with SQLite DBs, SQLite Scripts & Triggers, Stored SQLite Procedures

  1. 1. MobiCom on Android XML DB Specifications, OOP DB Modeling, Image Storage & Retrieval with SQLite DBs, SQLite Scripts & Triggers, Stored SQLite Procedures Vladimir Kulyukinhttp://www.youtube.com/vkedco www.vkedco.blogspot.com
  2. 2. Outline ● XML DB Specs, Java Objects, and SQLite Databases ● Image Storage & Retrieval with SQLite Databases ● SQLite Scripts & Triggers ● Stored SQLite Query Procedureshttp://www.youtube.com/vkedco http://www.vkedco.blogspot.com
  3. 3. XML DB Specs, Java Objects, & SQLite Databases source code is herehttp://www.youtube.com/vkedco http://www.vkedco.blogspot.com
  4. 4. BOOK_TITLE Table Database Schema ID | Title | BookAuthor | Translator | ISBN | Price Data Rows 1|The Essential Rumi|Jalal adDin Rumi|C. Barks, J. Moyne|9780062509581|17.51 2|The Illuminated Rumi|Jalal adDin Rumi|C. Barks|9780767900027|25.04 3|A Year with Rumi: Daily Readings|Jalal adDin Rumi|C. Barks|9780060845971|14.92 4|A Year with Hafiz: Daily Contemplations|Hafiz|D. Ladinsky|9780143117544|12.24 5|The Gift|Hafiz|Daniel Ladinsky|9780140195811|12.24http://www.youtube.com/vkedco www.vkedco.blogspot.com
  5. 5. BOOK_AUTHOR Table Database Schema ID | Name | BirthYear | DeathYear | Country Data Rows 1|Jalal adDin Rumi|1207|1273|Persia 2|Hafiz|1325|1389|Persiahttp://www.youtube.com/vkedco www.vkedco.blogspot.com
  6. 6. BOOK_COVER_IMAGE Table Database Schema ISBN | Image (BLOB) Data Rows 9780062509581|BLOB_01 9780767900027|BLOB_02 9780060845971|BLOB_03 9780143117544|BLOB_04 9780140195811|BLOB_05http://www.youtube.com/vkedco www.vkedco.blogspot.com
  7. 7. Image Blobshttp://www.youtube.com/vkedco www.vkedco.blogspot.com
  8. 8. BOOK_ORDER Table Database Schema ID|ISBN|FirstName|LastName|Price Data Rows 1|9780062509581|J.|A.|17.51 2|9780062509581|J.|A.|17.51 3|9780767900027|V.|K.|25.04 4|9780143117544|M.|N.|12.24 5|9780140195811|K.|R.|12.24 6|9780060845971|K.|R.|14.92 7|9780062509581|K.|R.|17.51http://www.youtube.com/vkedco www.vkedco.blogspot.com
  9. 9. Data Management Model XML Java Objects SQLite DB GUIhttp://www.youtube.com/vkedco www.vkedco.blogspot.com
  10. 10. XML ↔ Java XML Java <string-array name="book_cover_image_table"> public class BookCoverImage { <item>9780062509581;essential_rumi_cover</item> protected String mISBN; protected byte[] mCoverRef; <item>9780767900027;illuminated_rumi_cover</item> public BookCoverImage(String isbn, byte[] coverRef) { <item>9780060845971;year_with_rumi_cover</item> mISBN = isbn; mCoverRef = coverRef; <item>9780143117544;year_with_hafiz_cover</item> } <item>9780140195811;the_gift_cover</item> public String getISBN() { return mISBN; } </string-array> public byte[] getCoverRef() { return mCoverRef; } }http://www.youtube.com/vkedco www.vkedco.blogspot.com
  11. 11. Getting XML DB Specs // Populate book cover images public static String[] getXMLTableSpecs(Context cntxt, int table_name) { Resources mRes = cntxt.getResources(); switch ( table_name ) { // R.array.book_title_table, etc are XML string array constants case R.array.book_title_table: return mRes.getStringArray(R.array.book_title_table); case R.array.book_author_table: return mRes.getStringArray(R.array.book_author_table); case R.array.book_cover_image_table: return mRes.getStringArray(R.array.book_cover_image_table); case R.array.book_order_table: return mRes.getStringArray(R.array.book_order_table); default: return null; } }http://www.youtube.com/vkedco www.vkedco.blogspot.com
  12. 12. Java Object Creation private static BookCoverImage createBookCoverImageObject(Context cntxt, String isbn, String cover_img_reference) { Bitmap bmp = null; Resources mRes = cntxt.getResources(); if ( cover_img_reference.equals(mRes.getString(R.string.essential_rumi_cover)) ) { bmp = BitmapFactory.decodeResource(mRes, R.drawable.essential_rumi_cover); } else if ( cover_img_reference.equals(mRes.getString(R.string.illuminated_rumi_cover)) ) { bmp = BitmapFactory.decodeResource(mRes, R.drawable.illuminated_rumi_cover); } // Handle rest of cases // Create bitmap bytes ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] bitmapbytes = null; bmp.compress(CompressFormat.PNG, 0, bos); bitmapbytes = bos.toByteArray(); bmp.recycle(); try { bos.close(); } catch (IOException e) { e.printStackTrace(); } return new BookCoverImage(isbn, bitmapbytes); }http://www.youtube.com/vkedco www.vkedco.blogspot.com
  13. 13. Java Object DB Insertion // Populate book cover images String[] book_cover_image_table = getXMLTableSpecs(cntxt, R.array.book_cover_image_table); String[] book_cover_entry_parts; for(String book_cover_entry: book_cover_image_table) { book_cover_entry_parts = book_cover_entry.trim().split(XML_ENTRY_SEPARATOR); dbAdptr.insertUniqueBookCoverImage(createBookCoverImageObject( cntxt, book_cover_entry_parts[0], // books isbn book_cover_entry_parts[1] // books cover image reference ) ); }http://www.youtube.com/vkedco www.vkedco.blogspot.com
  14. 14. Java Object DB Insertion public long insertUniqueBookCoverImage(BookCoverImage bci) { byte[] bitmapbytes = bci.getCoverRef(); // we assume that bitmapbytes is not null ContentValues newBookCoverRef = new ContentValues(); newBookCoverRef.put(BookDbAdptr.COVER_IMAGE_ISBN_COL_NAME, bci.getISBN()); newBookCoverRef.put(BookDbAdptr.COVER_IMAGE_IMG_COL_NAME, bitmapbytes); return mDb.insertWithOnConflict(BOOK_COVER_IMAGE_TABLE, null, newBookCoverRef, SQLiteDatabase.CONFLICT_REPLACE); }http://www.youtube.com/vkedco www.vkedco.blogspot.com
  15. 15. DB Cursor Objects ● Cursor object is a result set of a query ● A result set can be thought of as a table where each data row is a query response ● Number of elements in a result set can be found with Cursor.getCount() ● To move from data row to data row, one can use Cursor.moveToFirst() and Cursor.moveToNext()http://www.youtube.com/vkedco www.vkedco.blogspot.com
  16. 16. Cursor Manipulation Logic // 1. Obtain Cursor object Cursor crsr = db.query( query arguments); // 2. Check if result set has data rows if ( crsr.getCount() != 0 ) { // 3. Move to 1st data row crsr.moveToFirst(); while ( crsr.isAfterLast() == false ) { // 4. Do data row processing logic // 5. Move to next data row crsr.moveToNext(); } }http://www.youtube.com/vkedco www.vkedco.blogspot.com
  17. 17. Image Store & Retrieval with SQLite Databaseshttp://www.youtube.com/vkedco http://www.vkedco.blogspot.com
  18. 18. SQLite BLOB ● SQLite has the data type BLOB ● The BLOB data type allows for the persistence and retrieval of arbitrary binary data ● If you need to store and retrieve images, BLOBs come in handy ● The only trick is accurately encoding/decoding them into/from byte arrayshttp://www.youtube.com/vkedco www.vkedco.blogspot.com
  19. 19. Image Storage Steps ● Get an image from a resource (local file, remote file, URI, etc) ● Create a Bitmap from the image ● Create a ByteArrayOutputStream ● Compress the Bitmap with a specific format into the ByteArrayOutputStream ● Convert the ByteArrayOutputStream into a byte array ● Persist the byte array into a SQLite databasehttp://www.youtube.com/vkedco www.vkedco.blogspot.com
  20. 20. Summary of Coding Steps Bitmap bmp = null; Resources mRes = cntxt.getResources(); // 1. decode resource into a Bitmap bmp = BitmapFactory.decodeResource(mRes, R.drawable.essential_rumi_cover); // 2. create a ByteArrayOutputStream ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] bitmapbytes = null; // 3. compress Bitmap into ByteArrayOutputStream bmp.compress(CompressFormat.PNG, 0, bos); // 4. convert ByteArrayOutputStream to byte array bitmapbytes = bos.toByteArray();http://www.youtube.com/vkedco www.vkedco.blogspot.com
  21. 21. SQLite Scripts & Triggershttp://www.youtube.com/vkedco http://www.vkedco.blogspot.com
  22. 22. SQLite Triggers ● A trigger is an SQLite procedure (script) that can be attached to specific events ● Typically triggers are associated with insertions, upgrades, and deletions ● It is possible to write trigger scripts and then associate them with databaseshttp://www.youtube.com/vkedco www.vkedco.blogspot.com
  23. 23. Sample Table: my_math_tbl ID first_name last_name research_area birth_year dearth_year time_stamp 1 kurt godel number theory 1906 1978 2012-10-25 18:11:10 Let us assume that we have added this table to book_info.db and now want to add a trigger script that will trigger after each insertion to update the time_stamp value.http://www.youtube.com/vkedco http://www.vkedco.blogspot.com
  24. 24. Sample Trigger Script: table_script -- sample sqlite script for creating my_math_tbl CREATE TABLE my_math_tbl (id INTEGER PRIMARY KEY, first_name TEXT not null, last_name TEXT not null, research_area TEXT not null, birth_year INTEGER not null, death_year INTEGER not null, time_stamp DATE); CREATE TRIGGER insert_math_time_stamp AFTER INSERT ON my_math_tbl BEGIN UPDATE my_math_tbl SET time_stamp = DATETIME(NOW) WHERE rowid = new.rowid; END;http://www.youtube.com/vkedco www.vkedco.blogspot.com
  25. 25. Trigger Activation ● The sample script table_script triggers on insertions and udpates a date value in a newly inserted record ● This is how we associate a table_script (given on the previous slide) with a database; ● sqlite3 book_info.db < table_script; ● Let us insert a record and see if the trigger script triggers ● sqlite> insert into my_math_tbl (id, first_name, last_name, research_area, birth_year, death_year) values (1, kurt, godel, number theory, 1906, 1978); ● sqlite> select * from my_math_tbl; ● select * from my_math_tbl; ● 1|kurt|godel|number theory|1906|1978|2012-10-25 18:11:32http://www.youtube.com/vkedco www.vkedco.blogspot.com
  26. 26. Stored SQLite Procedures source code is herehttp://www.youtube.com/vkedco http://www.vkedco.blogspot.com
  27. 27. SQLite Stored Procedures ● A stored procedure is a piece of compute code (written in specific programming language) that is repeatedly executed on a specific database ● Stored procedures are often more efficient because they by-pass SQL compilation ● Stored procedures are safer because they can implement addition data compliance and verification checkshttp://www.youtube.com/vkedco www.vkedco.blogspot.com
  28. 28. Sample Table 01: Book Title ID Title Author Translator ISBN Price 1 The Essential Rumi Jalal al-Din Rumi C. Barks, J. Moyne 9780062509581 17.51 2 The Illuminated Rumi Jalal al-Din Rumi C. Barks 9780767900027 25.04 3 A Year with Rumi: Daily Jalal al-Din Rumi C. Barks 9780060845971 14.92 Readings 4 A Year with Hafiz: Daily Hafiz D. Ladinsky 9780143117544 12.24 Contemplations 5 The Gift Hafiz D. Ladinsky 9780140195811 12.24 Let us implement a stored procedure that executes SELECT * FROM book_titlehttp://www.youtube.com/vkedco http://www.vkedco.blogspot.com
  29. 29. SQLiteDatabase.query() SQLiteDatabase db; Cursor crsr = db.query(String table, // table name String[] columns, // array of column names String[] selectionArgs, // array of selection args String groupBy, // SQL GROUP BY clause String having, // SQL HAVING clause String orderBy // SQL ORDER BY clause );http://www.youtube.com/vkedco www.vkedco.blogspot.com
  30. 30. sample_query_01: Part 01 String sample_query_01() { Cursor rslt = mDb.query(BOOK_TITLE_TABLE, // table name null, // column names null, // where clause null, // selection args null, // group by null, // having null); // order by StringBuffer buffer = new StringBuffer(""); buffer.append("QUERY 01nn"); // rest of code on text slide }http://www.youtube.com/vkedco www.vkedco.blogspot.com
  31. 31. sample_query_01: Part 02 if ( rslt.getCount() != 0 ) { rslt.moveToFirst(); while ( rslt.isAfterLast() == false ) { int id = rslt.getInt(rslt.getColumnIndex(BOOK_ID_COL_NAME)); String book_title = rslt.getString(rslt.getColumnIndex(BOOK_TITLE_COL_NAME)); String book_author = rslt.getString(rslt.getColumnIndex(BOOK_AUTHOR_COL_NAME)); String book_translator = rslt.getString(rslt.getColumnIndex(BOOK_TRANSLATOR_COL_NAME)); String book_isbn = rslt.getString(rslt.getColumnIndex(BOOK_ISBN_COL_NAME)); float book_price = rslt.getFloat(rslt.getColumnIndex(BOOK_PRICE_COL_NAME)); // continued on the next slidehttp://www.youtube.com/vkedco www.vkedco.blogspot.com
  32. 32. Example: sample_query_02() static final String SQL_QUERY_02 = "SELECT Name, BirthYear FROM book_author"; static final String[] QUERY_02_COLNAMES = new String[]{AUTHOR_NAME_COL_NAME, AUTHOR_BIRTH_YEAR_COL_NAME}; SQLiteDatabase db = this.getReadableDatabase(); Cursor crsr = db.query(BOOK_AUTHOR_TABLE, // table name QUERY_02_COLNAMES, // column names null, // where clause null, // selection args null, // group by null, // having null); // order byhttp://www.youtube.com/vkedco www.vkedco.blogspot.com
  33. 33. sampel_query_03: Part 03 buffer.append("ID = " + id + "n"); buffer.append("TITLE = " + book_title + "n"); buffer.append("AUTHOR = " + book_author + "n"); buffer.append("TRANSLATOR = " + book_translator + "n"); buffer.append("ISBN = " + book_isbn + "n"); buffer.append("PRICE = " + book_price + "n"); buffer.append("=====================n"); rslt.moveToNext(); } // end of while }// end of if-then rslt.close(); return buffer.toString(); } // end of query_01http://www.youtube.com/vkedco www.vkedco.blogspot.com
  34. 34. Example: sample_query_05() static final String SQL_QUERY_05 = "SELECT Title, Translator, Price FROM book_title WHERE Price < 15 or Translator=C. Barks ORDER BY Price DESC"; static final String[] QUERY_05_COLNAMES = new String[]{BOOK_TITLE_COL_NAME, BOOK_TRANSLATOR_COL_NAME, BOOK_PRICE_COL_NAME}; static final String QUERY_05_WHERE_CLAUSE = "Price < ? OR Translator = ?"; static final String[] QUERY_05_SELECTION_ARGS = new String[]{"15", "C. Barks"}; static final String QUERY_05_ORDER_BY = BOOK_PRICE_COL_NAME + " DESC"; SQLiteDatabase db = this.getReadableDatabase(); Cursor crsr = db.query(BOOK_TITLE_TABLE, // table name QUERY_05_COLNAMES, // column names QUERY_05_WHERE_CLAUSE, // where clause QUERY_05_SELECTION_ARGS, // selection args null, // group by null, // having BOOK_PRICE_COL_NAME + " DESC"); // order byhttp://www.youtube.com/vkedco www.vkedco.blogspot.com
  35. 35. Example: sample_query_06() static final String SQL_QUERY_06 = "SELECT ISBN, SUM(Price) FROM book_order GROUP BY ISBN ORDER BY Sum(Price) DESC;"; static final String[] QUERY_06_COLNAMES = new String[]{BOOK_ORDER_ISBN_COL_NAME, "SUM(Price)"}; static final String QUERY_06_GROUP_BY = BOOK_ORDER_ISBN_COL_NAME; static final String QUERY_06_ORDER_BY = "SUM(Price) DESC"; SQLiteDatabase db = this.getReadableDatabase(); Cursor crsr = db.query(BOOK_ORDER_TABLE, // table name QUERY_06_COLNAMES, // column names null, // where clause null, // selection args QUERY_06_GROUP_BY, // group by null, // having QUERY_06_ORDER_BY); // order byhttp://www.youtube.com/vkedco www.vkedco.blogspot.com
  36. 36. Example: sample_query_07() static final String SQL_QUERY_07 = "SELECT LastName, SUM(Price) FROM book_order GROUP BY LastName HAVING SUM(Price) > 20 ORDER BY SUM(Price) DESC;"; static final String[] QUERY_07_COLNAMES = new String[]{BOOK_ORDER_CLN_COL_NAME, "SUM(Price)"}; static final String QUERY_07_GROUP_BY = BOOK_ORDER_CLN_COL_NAME; static final String QUERY_07_HAVING = "SUM(Price) > 20"; static final String QUERY_07_ORDER_BY = "SUM(Price) DESC"; SQLiteDatabase db = this.getReadableDatabase(); Cursor crsr = db.query(BOOK_ORDER_TABLE, // table name QUERY_07_COLNAMES, // column names null, // where clause null, // selection args QUERY_07_GROUP_BY, // group by QUERY_07_HAVING, // having QUERY_07_ORDER_BY); // order byhttp://www.youtube.com/vkedco www.vkedco.blogspot.com
  37. 37. References ● www.sqlite.org/datatype3.html ● http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html ● http://souptonuts.sourceforge.net/readme_sqlite_tutorial.htmlhttp://www.youtube.com/vkedco www.vkedco.blogspot.com

×