Presentation is loading. Please wait.

Presentation is loading. Please wait.

Data Storage: Part 3 (SQLite)

Similar presentations


Presentation on theme: "Data Storage: Part 3 (SQLite)"— Presentation transcript:

1 Data Storage: Part 3 (SQLite)

2 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

3 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

4 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

5 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

6 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

7 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

8 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 device C:>adb -s emulator-5554 shell generic_x86:/ $ su generic_x86:/ # sqlite3 /data/data/edu.citadel.android.emergency/databases/emergency.db SQLite version :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

9 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

10 Example: Using the sqlite3 Command-Line
sqlite> .mode column sqlite> .width sqlite> .headers on sqlite> select * from emergency_contacts; _id name phone_num Emergency Consolidated Di Home Mary - Home Jim - Cell Billy - Cell Monica - Home Tommy - Cell sqlite> ©SoftMoore Consulting

11 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

12 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

13 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

14 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

15 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

16 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

17 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

18 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

19 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

20 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

21 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

22 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

23 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

24 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

25 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

26 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

27 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

28 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

29 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

30 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

31 Relevant Links Data Storage Class SQLiteDatabase
Class SQLiteDatabase Class SQLiteOpenHelper SQLite (home page) Android Database Example Appendix E - SQL Primer PowerPoint slides for this course ©SoftMoore Consulting


Download ppt "Data Storage: Part 3 (SQLite)"

Similar presentations


Ads by Google