Friday, 27 March 2015



1. SQLite and Android

What is SQLite?

SQLite is an Open Source database. SQLite supports standard relational database features like SQL syntax, transactions and prepared statements. The database requires limited memory at runtime (approx. 250 KByte) which makes it a good candidate from being embedded into other runtimes.
SQLite supports the data types TEXT (similar to String in Java), INTEGER (similar to long in Java) and REAL(similar to double in Java). All other types must be converted into one of these fields before getting saved in the database. SQLite itself does not validate if the types written to the columns are actually of the defined type, e.g. you can write an integer into a string column and vice versa.

SQLite in Android

SQLite is embedded into every Android device. Using an SQLite database in Android does not require a setup procedure or administration of the database.
You only have to define the SQL statements for creating and updating the database. Afterwards the database is automatically managed for you by the Android platform.
Access to an SQLite database involves accessing the file system. This can be slow. Therefore it is recommended to perform database operations asynchronously.
If your application creates a database, this database is by default saved in the directoryDATA/data/APP_NAME/databases/FILENAME.
The parts of the above directory are constructed based on the following rules. DATA is the path which theEnvironment.getDataDirectory() method returns. APP_NAME is your application name. FILENAME is the name you specify in your application code for the database.


Creating and updating database with SQLiteOpenHelper

To create and upgrade a database in your Android application you create a subclass of the SQLiteOpenHelperclass. In the constructor of your subclass you call the super() method of SQLiteOpenHelper, specifying the database name and the current database version.
In this class you need to override the following methods to create and update your database.
  • onCreate() - is called by the framework, if the database is accessed but not yet created.
  • onUpgrade() - called, if the database version is increased in your application code. This method allows you to update an existing database schema or to drop the existing database and recreate it via theonCreate() method.
Both methods receive an SQLiteDatabase object as parameter which is the Java representation of the database.
The SQLiteOpenHelper class provides the getReadableDatabase() and getWriteableDatabase()methods to get access to an SQLiteDatabase object; either in read or write mode.
The database tables should use the identifier _id for the primary key of the table. Several Android functions rely on this standard.



SQLiteDatabase is the base class for working with a SQLite database in Android and provides methods to open, query, update and close the database.
More specifically SQLiteDatabase provides the insert()update() and delete() methods.
In addition it provides the execSQL() method, which allows to execute an SQL statement directly.
The object ContentValues allows to define key/values. The key represents the table column identifier and thevalue represents the content for the table record in this column. ContentValues can be used for inserts and updates of database entries.
Queries can be created via the rawQuery() and query() methods or via the SQLiteQueryBuilder class .
rawQuery() directly accepts an SQL select statement as input.
query() provides a structured interface for specifying the SQL query.
SQLiteQueryBuilder is a convenience class that helps to build SQL queries.



rawQuery() Example

The following gives an example of a rawQuery() call.

return database.query(DATABASE_TABLE, 
  new String[] { KEY_ROWID, KEY_CATEGORY, KEY_SUMMARY, KEY_DESCRIPTION }, 
  null, null, null, null, null);
 


Parameters of the query() method
ParameterComment
String dbNameThe table name to compile the query against.
String[] columnNamesA list of which table columns to return. Passing "null" will return all columns.
String whereClauseWhere-clause, i.e. filter for the selection of data, null will select all data.
String[] selectionArgsYou may include ?s in the "whereClause"". These placeholders will get replaced by the values from the selectionArgs array.
String[] groupByA filter declaring how to group rows, null will cause the rows to not be grouped.
String[] havingFilter for the groups, null means no filter.
String[] orderByTable columns which will be used to order the data, null means no ordering.

If a condition is not required you can pass null, e.g. for the group by clause.
The "whereClause" is specified without the word "where", for example a "where" statement might look like: "_id=19 and summary=?".
If you specify placeholder values in the where clause via ?, you pass them as the selectionArgs parameter to the query.


3.6. Cursor

A query returns a Cursor object. A Cursor represents the result of a query and basically points to one row of the query result. This way Android can buffer the query results efficiently; as it does not have to load all data into memory.
To get the number of elements of the resulting query use the getCount() method.
To move between individual data rows, you can use the moveToFirst() and moveToNext() methods. TheisAfterLast() method allows to check if the end of the query result has been reached.
Cursor provides typed get*() methods, e.g. getLong(columnIndex)getString(columnIndex) to access the column data for the current position of the result. The "columnIndex" is the number of the column you are accessing.
Cursor also provides the getColumnIndexOrThrow(String) method which allows to get the column index for a column name of the table.
Cursor needs to be closed with the close() method call.

Cursor is not a class but an interface. If your Cursor object is from a SQLite query, it is a SQLiteCursor. In that definition (\Android\android-sdk\source\android\database\sqlite\SQLiteCursor.java)close() is called in the finalize() function. This may be different in other cursor types, since the Cursor interface does not specify this behavior.

You can close the cursor once you have retrieved the values for that particular object inside your method.

 ListViews, ListActivities and SimpleCursorAdapter

ListViews are Views which allow to display a list of elements.
ListActivities are specialized activities which make the usage of ListViews easier.
To work with databases and ListViews you can use the SimpleCursorAdapter. TheSimpleCursorAdapter allows to set a layout for each row of the ListViews.
You also define an array which contains the column names and another array which contains the IDs of Viewswhich should be filled with the data.
The SimpleCursorAdapter class will map the columns to the Views based on the Cursor passed to it.
To obtain the Cursor you should use the Loader class.

Haystack TV Doubles Engagement with Android TV | Android Developers Blog

Haystack TV Doubles Engagement with Android TV | Android Developers Blog