Your SlideShare is downloading. ×
  • Like
  • Save
MobAppDev (Fall 2013): Persistence of Structured Data on Android with SQLite
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×

Now you can save presentations on your phone or tablet

Available for both IPhone and Android

Text the download link to your phone

Standard text messaging rates apply

MobAppDev (Fall 2013): Persistence of Structured Data on Android with SQLite

  • 589 views
Published

 

Published in Technology
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
    Be the first to like this
No Downloads

Views

Total Views
589
On SlideShare
0
From Embeds
0
Number of Embeds
22

Actions

Shares
Downloads
0
Comments
0
Likes
0

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

  • 1. MobAppDev Persistence of Structured Data on Android with SQLite Vladimir Kulyukin www.vkedco.blogspot.com
  • 2. Outline ● ● ● ● ● Persisting of Structured Data with SQL Databases Lite Intro to SQLite SQLite Database Inspection SQLite by Example Creation & Population of SQLite DB from XML
  • 3. Persistence of Structured Data with SQL Databases
  • 4. SharedPreferences: Pros & Cons ● Pros   ● Lightweight Easy to code and debug Cons  Slow with large data volumes  Not helpful with highly structured data when key/value pairs are insufficient  Entire file needs to be read and parsed to access data  Takes up more space because XML is used for storage
  • 5. SQL Databases: Pros & Cons ● Pros  Flexible with structured data   Robust: can handle incremental changes  ● Scalable: can handle large data volumes Responsive: can handle flexible queries Cons  Heavyweight: more code & more memory  Maintenance: harder to code & debug
  • 6. Database Design ● ● ● ● ● Standard database design practices also apply on Android A key design principle is to manage space well: reduction redundancy via database normalization The objective of database normalization is to decompose relations with anomalies to produce smaller, well structured relations Database design is more of an art than a science: takes experience & practice Helpful resource: en.wikipedia.org/Database_normalization
  • 7. Database Fundamentals ● ● ● ● ● Database is a persistent collection of structured data Data are structured because they are organized in tables A Table is similar to an Excel spreadsheet except that its columns have standard SQL data types (e.g., TEXT, INTEGER, FLOAT, etc.) In terms of Object-Oriented Modeling, each table represents an Class (e.g., Book, Author) and each column represents an Attribute Each table row represents an Object of a specific Class
  • 8. Sample Table 01: Book 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 Readings Jalal al-Din Rumi C. Barks 9780060845971 14.92 4 A Year with Hafiz: Daily Contemplations Hafiz D. Ladinsky 9780143117544 12.24 5 The Gift Hafiz D. Ladinsky 9780140195811 12.24 - Book is a Class - ID, Title, Author, Translator, ISBN, Price are Attributes - Rows 1 – 5 are Book Objects
  • 9. Sample Table 02: Author ID Name BirthYear DeathYear Country 1 Jalal al-Din Rumi 1207 1273 Persia 2 Hafiz 1325 1389 Persia - Author is a Class - ID, Name, BirthYear, DeathYear, Country, are Attributes - Row 1 is an Author Object - Row 2 is an Author Object
  • 10. The ID Column ● ● ● In many tables, the ID column represents the primary key The primary key is the key that uniquely identifies the row entry object When design an SQL table, it is typical (not necessary!) to specify the primary key as an integer and mark it as auto-incrementable: this way every inserted row is guaranteed to have a unique primary key
  • 11. Lite Intro to SQLite
  • 12. SQLite on Android ● ● ● ● ● Android offers SQLite relational database library Every application can create its own database over which it has complete control SQLite databases should be considered only when you need to manage complex, structured data Databases are stored in /data/data/<package_name>/databases/ Example: /data/data/org.vkedco.mobappdev.simple_db_app_01/databases/
  • 13. What is SQLite? ● ● ● SQLite is a relational database management system (RDBMS) SQLite is a compact C library that is part of the Android software stack Since it is a library, it can be integrated into each application without external dependencies: this simplifies transactions and synchronizations, minimizes latency
  • 14. Command Line DB Access ● Suppose that you have created a database (we will learn how to do this later) and want to interact with it 1. Open a command line 2. CD into platform-tools directory 3. Connect to the device (e.g., adb -e shell) 4. CD into the database directory: cd /data/data/<package>databases> 5. Execute: sqlite3 <database_name> (e.g. sqlite3 book_info.db) Now you can interct with book_info.db via sqlite shell 6. Execute .quit to quit
  • 15. Connecting to ADB
  • 16. CD Into Data/Data/<APP PACKAGE> 1. CD Into Data/Data/ 2. LS 3. Look for APP PACKAGE
  • 17. Start SQLite3 Interpreter
  • 18. Discovering TABLE Schemas ● ● A Table Schema is the specification of column values and types for a given table To access table schemas for a DB: 1. Get in to the sqlite shell 2. Execute: .schema You should see something like: CREATE TABLE android_metadata (locale TEXT); CREATE TABLE author (ID integer primary key autoincrement, Name text not null, ...); CREATE TABLE book (ID integer primary key autoincrement, Title text not null, ...);
  • 19. SQLite by Example
  • 20. Displaying Tables ● To display the entire table: SELECT * FROM <TABLE>; Examples:  SELECT * FROM BOOK;  SELECT * FROM AUTHOR;
  • 21. Project Columns ● To project the values of specific columns for each record: SELECT COLUM_NAME_1, …, COLUMN_NAME_n FROM <TABLE>; Examples:  SELECT Author, Title FROM BOOK;  SELECT Title, Author FROM BOOK;
  • 22. Record Retrieval ● To retrieve records with specific values, use the WHERE clause: SELECT COLUM_NAME_1, …, COLUMN_NAME_n FROM <TABLE> WHERE <COL_VAL_SPEC>; Examples:  SELECT Title FROM BOOK WHERE ID = 3;  SELECT Title, Author FROM BOOK WHERE ID < 3;
  • 23. Record Ordering ● To order records by attributes, use the ORDER BY clause: SELECT COLUM_NAME_1, …, COLUMN_NAME_n FROM <TABLE> ORDER BY COL_NAME Asc/Desc; Examples:  SELECT Title, Author FROM BOOK ORDER BY Price Asc;  SELECT Title, Author FROM BOOK ORDER BY Price Desc;
  • 24. Record Ordering ● To order records by attributes, use the ORDER BY clause: SELECT COLUM_NAME_1, …, COLUMN_NAME_n FROM <TABLE> ORDER BY COL_NAME Asc/Desc; Examples:  SELECT Title, Author FROM BOOK ORDER BY Price Asc;  SELECT Title, Author FROM BOOK ORDER BY Price Desc;
  • 25. Record Ordering ● To order records by attributes, use the ORDER BY clause: SELECT COLUM_NAME_1, …, COLUMN_NAME_n FROM <TABLE> ORDER BY COL_NAME Asc/Desc; Examples:  SELECT Title, Author FROM BOOK ORDER BY Price Asc;  SELECT Title, Author FROM BOOK ORDER BY Price Desc;
  • 26. SQL vs SQLite Data Typing ● ● ● ● SQL engines typically use static typing: datatype of a value is determined by the column in which the value is stored SQLite engines use dynamic typing: datatype of a value is associated with the value not the column in which it is stored Basic SQL vs. SQLite tradeoff: security and safety (SQL) vs. flexibility (SQLite) SQLite rule of thumb: do not expose your SQLite API to third parties
  • 27. SQLite Datatypes ● ● ● ● ● NULL – the value is NULL INTEGER – signed integers; signed integer can be stored as 1, 2, 3, 4, 5, 6, or 8 bytes; the storage size depends on the value magnitude REAL – float-point numbers; stored as 8 bytes TEXT – text string; stored according to the database encoding (e.g., UTF-8) BLOB – data blob, typically stored as array of bytes
  • 28. Creation & Population of SQLite DB from XML
  • 29. Simple Book DB Application Write an Android application that creates and populates an SQLite database from an XML specification of the book title and book author tables. source code is here
  • 30. Object-Oriented Data Modeling: Modeling Tables as Java Classes
  • 31. Book Table as Book Class public class Book { protected String mTitle; protected String mAuthor; protected String mTranslator; protected String mISBN; protected float mPrice; // rest of code } source code is in Book.java
  • 32. Author Table as Author Class public class Author { protected String mName; protected int mBirthYear; protected int mDeathYear; protected String mCountry; // rest of code } source code is in Author.java
  • 33. Obtaining XML Specifications of DB Tables
  • 34. XML DB Table Specs ● ● ● ● XML DB table specs can come in a variety of formats and from a variety of resources Basically, each table spec must describe inflatable row records; table specs inflated into table Java objects Table specs give you the flexibility to persist (save) Java into SQLite databases or Object databases Source of table specs can vary from local XML files, remote XML files, RSS feeds, etc
  • 35. XML Specs of Book Title Table <string-array name="book_title_table"> <item>The Essential Rumi;Jalal adDin Rumi;C. Barks, J. Moyne;9780062509581;17.51</item> <item>The Illuminated Rumi;Jalal adDin Rumi;C. Barks;9780767900027;25.04</item> <item>A Year with Rumi: Daily Readings;Jalal adDin Rumi;C. Barks;9780060845971;14.92</item> <item>A Year with Hafiz: Daily Contemplations;Hafiz;D. Ladinsky;9780143117544;12.24</item> <item>The Gift;Hafiz;Daniel Ladinsky;9780140195811;12.24</item> </string-array> XML source is in strings.xml
  • 36. XML Specs of Book Author Table <string-array name="book_author_table"> <item>Jalal adDin Rumi;1207;1273;Persia</item> <item>Hafiz;1325;1389;Persia</item> </string-array> XML source is in strings.xml
  • 37. Design & Implementation of Database Adapters
  • 38. DB XML Specs Table Inflation ● ● ● Typically there is a class that creates objects from XML table specs In our case, we simply inflate XML string-arrays given in strings.xml and create objects from XML strings Each object is then given to the database adapter (BookDbAdptr.java) for SQLite persistence
  • 39. Population of SQLite DB ● ● ● Once we have an adapter class, we can use it to populate the SQLite DB This is done in BookDbAct01.java by the method populateBookList() This method parses XML, creates Book and Author objects and uses the methods insertUniqueBook() and insertUniqueAuthor() defined of BookDbAdptr.java
  • 40. Population of SQLite DB // 1. open db dbAdptr.open(); // 2. Read XML arrays String[] book_table = mRes.getStringArray(R.array.book_table); String[] author_table = mRes.getStringArray(R.array.author_table); source code is in BookDbAct01.java
  • 41. Population of SQLite DB // 3. Inflate book table xml specs into Book objects String[] book_entry_parts; for(String book_entry: book_table) { book_entry_parts = book_entry.trim().split(XML_ENTRY_SEPARATOR); dbAdptr.insertUniqueBook(new Book(book_entry_parts[0], // title book_entry_parts[1], // author book_entry_parts[2], // translator book_entry_parts[3], // isbn Float.parseFloat(book_entry_parts[4]) // price )); } source code is in BookDbAct01.java
  • 42. Population of SQLite DB // 3. Inflate author table xml specs into Author objects and insert them into DB String[] author_entry_parts; for(String author_entry: author_table) { author_entry_parts = author_entry.trim().split(XML_ENTRY_SEPARATOR); dbAdptr.insertUniqueAuthor( new Author(author_entry_parts[0], // author's name Integer.parseInt(author_entry_parts[1]), // author's birth year Integer.parseInt(author_entry_parts[2]), // author's death year author_entry_parts[3]) // author's country ); } // 4. Close db dbAdptr.close(); source code is in BookDbAct01.java
  • 43. References ● en.wikipedia.org/Database_normalization ● http://developer.android.com/tools/help/adb.html ● http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html