Data Storage: Part 3 (SQLite)

Slides:



Advertisements
Similar presentations
Programming with Android: Data management
Advertisements

CE881: Mobile and Social Application Programming Flexible Data Handling with Integrity: SQLite Simon M. Lucas.
SQLite is a software library. It is: self-contained + Serverless + zero-configuration transactional = SQL database engine. Most widely deployed. The source.
 data/data-storage.html#pref data/data-storage.html#pref 
SQLite in Mobile Apps by Dan Youberg. Overview Many well known applications and Internet browsers use SQLite due to its very small size (~250 Kb). Also.
CONTENT PROVIDER. Content Provider  A content provider makes a specific set of the application's data available to other applications => Share data to.
Cosc 5/4730 Android and Blackberry SQLite. For the sql language syntax, please see SQlite documentation –
SQLLite and Java CS-328 Dick Steflik. SQLLite Embedded RDBMS ACID Compliant Size – about 257 Kbytes Not a client/server architecture –Accessed via function.
Phonegap Bridge – File System CIS 136 Building Mobile Apps 1.
CS378 - Mobile Computing Persistence - SQLite. Databases RDBMS – relational data base management system Relational databases introduced by E. F. Codd.
Introduction To Databases IDIA 618 Fall 2014 Bridget M. Blodgett.
Data Persistence in Android
SQLite Database. SQLite Public domain database – Advantages Small (about 150 KB) – Used on devices with limited resources Each database contained within.
Database Rung-Hung Gau Department of Computer Science and Engineering
Data Storage: Part 3 (SQLite)
Cosc 5/4730 Android Content Providers and Intents.
Data Storage: Part 4 (Content Providers). Content Providers Content providers allow the sharing of data between applications. Inter-process communication.
COMP 365 Android Development.  Manages access from a central database  Allows multiple applications to access the same data.
SQLite Android Club SQLite About onCreate Insert Select Update Delete onUpdate.
SQLite Supported by BlackBerry OS 5.0 Using SQLite.
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.
Address Book App 1. Define styles   Specify a background for a TextView – res/drawable/textview_border.xml.
9 Persistence - SQLite CSNB544 Mobile Application Development Thanks to Utexas Austin.
JDBC. Java.sql.package The java.sql package contains various interfaces and classes used by the JDBC API. This collection of interfaces and classes enable.
Persistence Dr. David Janzen Except as otherwise noted, the content of this presentation is licensed under the Creative Commons Attribution 2.5 License.
SQLite (part deux) 1 CS440. Traditional Model View Controller (MVC) CS440 2.
Mobile Software Development ISCG 7424 Department of Computing UNITEC John Casey and Richard Rabeder SQLite and Permissions.
Li Tak Sing COMPS311F. Database programming JDBC (Java Database Connectivity) Java version of ODBC (Open Database Connectivity) ODBC provides a standard.
SQLite DB Storing Data in Android RAVI GAURAV PANDEY 1.
Android - SQLite Database 12/10/2015. Introduction SQLite is a opensource SQL database that stores data to a text file on a device. Android comes in with.
SQlite. SQLite is a opensource SQL database that stores data to a text file on a device. Android comes in with built in SQLite database implementation.
CHAPTER 9 File Storage Shared Preferences SQLite.
Android Storage MAY 2013 Hu.Cai. NAME OF PRESENTATION [CHANGE IN SLIDE MASTER] MONTH, YEAR [CHANGE IN SLIDE MASTER] Outline 1.Storage In General 2.SharedPreferences.
By: Eliav Menachi.  On Android, all application data (including files) are private to that application  Android provides a standard way for an application.
CMPE419 Mobile Application Development Asst.Prof.Dr.Ahmet Ünveren SPRING Computer Engineering Department Asst.Prof.Dr.Ahmet Ünveren
Introduction to Database Programming with Python Gary Stewart
CS371m - Mobile Computing Persistence - SQLite. 2 In case you have not taken 347: Data Management or worked with databases as part of a job, internship,
Content Providers.
CS499 – Mobile Application Development
Making content providers
Content provider.
Cosc 5/4730 Sqlite primer.
Android Content Providers & SQLite
Mobile Applications (Android Programming)
Data Storage: Part 4 (Content Providers)
SQLite in Android Landon Cox March 2, 2017.
JDBC – Java Database Connectivity
Mobile Software Development for Android - I397
Mobile Application Development BSCS-7 Lecture # 18, 19
CIS 136 Building Mobile Apps
ListView: Part 2.
Mobile Applications (Android Programming)
Android Application SQLite 1.
Reactive Android Development
CS499 – Mobile Application Development
Android Database using SQLite
Mobile Application Development Chapter 5 [Persistent Data in Android]
Mobile Computing With Android ACST Android Database Storage Part 2
Android Programming Lecture 7
CMPE419 Mobile Application Development
CS371m - Mobile Computing Persistence - SQLite.
CIS 136 Building Mobile Apps
CMPE419 Mobile Application Development
Mobile Computing With Android ACST 4550 Android Database Storage
Computer Science Projects Database Theory / Prototypes
Android Developer Fundamentals V2
ListView A view that shows items in a vertically scrolling list. The items come from the ListAdapter associated with this view. ListAdapter is used to.
Department of School of Computing and Engineering
SQLLite and Android.
Mobile Programming Dr. Mohsin Ali Memon.
Presentation transcript:

Data Storage: Part 3 (SQLite)

SQLite SQLite is a software library that provides full relational database capability for Android applications. Each application that uses SQLite has its own instance of the database, which is by default accessible only from the application itself. The database is stored in the following folder: /data/data/<package-name>/databases A Content Provider can be used to share the database information with other applications. ©SoftMoore Consulting

Features of SQLite ACID transactions (atomic, consistent, isolated, and durable) Zero-configuration – no setup or administration. Implements most of SQL92. Complete database is stored in a single file. Supports terabyte-sized databases and gigabyte-sized strings and blobs. Small code footprint (less than 325KB fully configured). Self-contained: no external dependencies. C source code is in the public domain. ©SoftMoore Consulting

SQLite Datatypes Most SQL database systems use static typing; i.e., the type of a value is determined by the column in which the value is stored. SQLite uses a more general dynamic type system – the type of a value is associated with the value itself, not with its column. Think of column types as hints. It is possible to store a string in an integer column and vice versa. ©SoftMoore Consulting

SQLite Datatypes (continued) Each value stored in an SQLite database has one of the following storage classes: NULL. The value is a NULL value. INTEGER. The value is a signed integer, stored in 1, 2, 3, 4, 6, or 8 bytes depending on the magnitude of the value. REAL. The value is a floating point value, stored as an 8-byte IEEE floating point number. TEXT. The value is a text string, stored using the database encoding (UTF-8, UTF-16BE or UTF-16LE). BLOB. The value is a blob of data, stored exactly as it was input. Note that a storage class is slightly more general than a type. ©SoftMoore Consulting

SQLite Datatypes (continued) Each column in a SQLite database is assigned one of the following type affinities: TEXT – NUMERIC INTEGER – REAL NONE SQLite does not have a separate Boolean storage class. Boolean values are stored as integers 0 (false) and 1 (true). SQLite does not have a storage class set aside for storing dates and/or times. Instead, the built-in date and time functions of SQLite are capable of storing dates and times as TEXT, REAL, or INTEGER values. ©SoftMoore Consulting

Using the sqlite3 Command-Line In addition to accessing a SQLite database from an Android application, it is also possible to interact with the database on a virtual device using the sqlite3 command-line tool via the Android Debug Bridge (ADB) remote shell. Preparation add environment variables ANDROID_SDK_HOME; e.g., C:\Java\Android\sdk ANDROID_AVD_HOME; e.g., C:\Users\jmoore\.android\avd add the following to your PATH environment variable: %ANDROID_AVD_HOME% %ANDROID_SDK_HOME% %ANDROID_SDK_HOME%\tools %ANDROID_SDK_HOME%\platform-tools Put this one first – above the others. ©SoftMoore Consulting

Using the sqlite3 Command-Line (continued) Start a virtual device (emulator) and launch the ADB shell to connect to the database from a command prompt. C:>adb devices List of devices attached emulator-5554 device C:>adb -s emulator-5554 shell generic_x86:/ $ su generic_x86:/ # sqlite3 /data/data/edu.citadel.android.emergency/databases/emergency.db SQLite version 3.9.2 2015-11-02 18:31:45 Enter ".help" for usage hints. sqlite> Enter SQL statements and commands at the prompt. SQL statements must be terminated by a semicolon. SQLite commands start with a period. Note: Does not work with a real device. response ©SoftMoore Consulting

Selected SQLite Commands .databases List names/files of attached databases .exit Exit this program .header(s) ON|OFF Turn display of headers on or off .help Show all SQLite commands .import FILE TABLE Import data from FILE into TABLE .mode column Left-aligned columns. (See .width) .read FILENAME Execute SQL in FILENAME .schema Show the CREATE statements .width NUM NUM … Set column widths for “column” mode ©SoftMoore Consulting

Example: Using the sqlite3 Command-Line sqlite> .mode column sqlite> .width 3 15 12 sqlite> .headers on sqlite> select * from emergency_contacts; _id name phone_num --- --------------- ------------ 1 Emergency - 911 911 2 Consolidated Di 843-743-7200 3 Home 123-456-7890 4 Mary - Home 234-567-8901 5 Jim - Cell 345-678-9012 6 Billy - Cell 456-789-0123 7 Monica - Home 567-890-1234 8 Tommy - Cell 567-890-1234 sqlite> ©SoftMoore Consulting

Developing Applications Using SQLite Primary classes and interfaces android.database.sqlite.SQLiteDatabase android.database.sqlite.SQLiteOpenHelper (abstract) android.database.Cursor (interface) Using adapters to connect data and views Understanding relational databases and SQL ©SoftMoore Consulting

Class SQLiteOpenHelper Class SQLiteOpenHelper is an abstract helper class in package android.database.sqlite that can be used to manage database creation and versioning. Class SQLiteOpenHelper will open the database if it exists create the database if it does not exist upgrade the database as necessary To use class SQLiteOpenHelper, create a subclass that overrides abstract methods onCreate() and onUpgrade(). Note: Database names must be unique within an application, not across all applications. ©SoftMoore Consulting

Selected Methods in Class SQLiteOpenHelper SQLiteOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) constructor to initialize a SQLiteOpenHelper object the factory parameter can be null for the default value void close() close an open database SQLiteDatabase getReadableDatabase() create and/or open a database for reading only SQLiteDatabase getWritableDatabase() create and/or open a database for both reading and writing ©SoftMoore Consulting

Selected Methods in Class SQLiteOpenHelper (continued) abstract void onCreate(SQLiteDatabase db) called when the database is created for the first time Note: You can “preload” a set of database values in this method. void onOpen(SQLiteDatabase db) called when the database is opened abstract void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) called when the database needs to be upgraded ©SoftMoore Consulting

Contract Class Applications that use a database and/or implement a content provider (see next section) often implement a “contract” class. A contract class defines constants that help applications work with the content URIs, column names, intent actions, and other features of a content provider. Contract classes are not included automatically with a provider; the provider’s developer has to define them and make them available to other developers. ©SoftMoore Consulting

Example: Contract Class public final class EmergencyDbContract { public static final String DB_NAME = "emergency.db"; public static final int DB_VERSION = 1; public static final String TABLE_NAME = "emergency_contacts"; public static final String[] COLUMNS = { "_id", "name", "phone_num" }; public static final String AUTHORITY = "edu.citadel.android.emergency"; public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/" + TABLE_NAME); private EmergencyDbContract() {} // prevent instantiation } Useful for adding a content provider. ©SoftMoore Consulting

Surrogate Primary Keys in SQLite In SQLite, a column with type INTEGER PRIMARY KEY is an alias for the ROWID. can be used as a surrogate key On an insert, if the integer primary key column is not explicitly given a value, then it will be filled in automatically by SQLite with an unsigned integer. SQLite provides an AUTOINCREMENT keyword that can be used in defining such a key, but ... it has slightly different semantics it imposes extra runtime overhead and should be avoided ©SoftMoore Consulting

Example: Using SQLiteOpenHelper public class EmergencyDbOpenHelper extends SQLiteOpenHelper { /** * Construct a SQLiteOpenHelper object for the * emergency database. */ public EmergencyDbOpenHelper(Context context) super(context, EmergencyDbContract.DB_NAME, null, EmergencyDbContract.DB_VERSION); } (continued on next slide) ©SoftMoore Consulting

Example: Using SQLiteOpenHelper (continued) @Override public void onCreate(SQLiteDatabase db) { String createSql = "create table " + EmergencyDbContract.TABLE_NAME + "(" + " _id integer primary key," + " name text not null," + " phone_num text not null" + ")"; db.execSQL(createSql); insertContacts(db); } (continued on next slide) ©SoftMoore Consulting

Example: Using SQLiteOpenHelper (continued) @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // This is version 1 so no actions are required. // Possible actions include dropping/recreating // tables, saving/restoring data in tables, etc. } private void insertContacts(SQLiteDatabase db) // perform inserts to initialize the database ©SoftMoore Consulting

Class SQLiteDatabase Defined in package android.database.sqlite Exposes methods to manage a SQLite database Has methods to create, delete, execute SQL commands, and to perform other common database management tasks Has several “convenience” methods for constructing SQL queries, inserts, etc. Alternatively, other methods can be used to directly execute SQL commands passed as string parameters. ©SoftMoore Consulting

Selected Methods in Class SQLiteDatabase void beginTransaction() begin a transaction int delete(String table, String whereClause, String[] whereArgs) convenience method for deleting rows from the database returns the number of rows affected if a where clause is passed in; 0 otherwise void endTransaction() end a transaction void execSQL(String sql) execute a single SQL statement that does not return data ©SoftMoore Consulting

Selected Methods in Class SQLiteDatabase (continued) long insert(String table, String nullColumnHack, ContentValues values) convenience method for inserting a row into the database returns the row ID of the newly inserted row, or -1 if an error occurred Cursor query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy) query the given table, returning a Cursor over the result set Cursor rawQuery(String sql, String[] selectionArgs) runs the provided SQL and returns a Cursor over the result set ©SoftMoore Consulting

Selected Methods in Class SQLiteDatabase (continued) int update(String table, ContentValues values, String whereClause, String[] whereArgs) convenience method for updating rows in the database returns the number of rows affected ©SoftMoore Consulting

Example: Using Query Methods in Class SQLiteDatabase SQLiteOpenHelper openHelper = new EmergencyDbOpenHelper(this); SQLiteDatabase db = openHelper.getReadableDatabase(); Query using convenience methods String tableName = "emergency_contacts"; String[] columns = {"name", "phone_num"}; String orderBy = "name"; Cursor cursor = db.query(tableName, columns, null, null, null, null, orderBy); Query using method rawQuery() String query = "select name, phone_num" + " from emergency_contacts" + " order by name"; Cursor cursor = db.rawQuery(query, null); ©SoftMoore Consulting

Example: Using Insert Methods in Class SQLiteDatabase SQLiteOpenHelper openHelper = new EmergencyDbOpenHelper(this); SQLiteDatabase db = openHelper.getWritableDatabase(); Insert using convenience methods String tableName = "emergency_contacts"; ContentValues values = new ContentValues(); values.put("name", "Emergency – 911"); values.put("phone_num", "911"); db.insert(tableName, null, values); Insert using method execSQL() String insertSql = "insert into emergency_contacts" + " (name, phone_num) values" + " (\"Emergency - 911\", \"911\")"; db.execSQL(insertSql); ©SoftMoore Consulting

Interface Cursor Interface Cursor (in package android.database) is used to iterate over the rows returned by a “select” query. analogous to a Java Iterator or a JDBC ResultSet Interface Cursor provides random read-write access to the result set returned by a database query. Methods in interface Cursor can be used to position the cursor within the result set (“move” methods) to retrieve column values from the row (“get” methods) to provide metadata about the query (e.g., getColumnNames()). ©SoftMoore Consulting

Selected Methods in Interface Cursor int getColumnIndex(String columnName) Returns zero-based index for the given column name double getDouble(int columnIndex) int getInt(int columnIndex) long getLong(int columnIndex) String getString(int columnIndex) boolean move(int offset) boolean moveToFirst() boolean moveToNext() boolean moveToPosition(int position) Returns the value of the requested column as the specified type. Moves the cursor as specified. ©SoftMoore Consulting

Using a Cursor Similar to using a JDBC ResultSet, initially a cursor is positioned before the first row. The various “move” methods can be used to move the cursor to a row. The moveToNext() method moves the cursor to the next row. Since it returns false when there are no more rows, it can be used in a while loop to iterate through the rows of a cursor. Example while (cursor.moveToNext()) { ... // retrieve/process data for one row } ©SoftMoore Consulting

Example: Using Interface Cursor SQLiteDatabase db = openHelper.getReadableDatabase(); String query = "select * from emergency_contacts"; Cursor cursor = db.rawQuery(query, null); while (cursor.moveToNext()) { int id = cursor.getInt(0); String name = cursor.getString(1); String phoneNum = cursor.getString(2); String message = "ID: " + id + ", Name: " + name + ", Phone Number: " + phoneNum; Toast toast = Toast.makeText(Emergency.this, message, Toast.LENGTH_SHORT); toast.show(); } ©SoftMoore Consulting

Relevant Links Data Storage Class SQLiteDatabase https://developer.android.com/guide/topics/data/data-storage.html Class SQLiteDatabase https://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html Class SQLiteOpenHelper https://developer.android.com/reference/android/database/sqlite/SQLiteOpenHelper.html SQLite (home page) http://www.sqlite.org/ Android Database Example http://examples.javacodegeeks.com/android/core/database/android-database-example/ Appendix E - SQL Primer PowerPoint slides for this course ©SoftMoore Consulting