Zybotech solutions, offers job oriented courses on mobile application development for freshers and professionals with placement assistance, interactive training sessions with live project exposure.
1. Android Application Development Training Tutorial
For more info visit
http://www.zybotech.in
A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
2. Accessing Data With Android Cursors
What is SQLite
SQLite is an open-source server-less database engine. SQLite supports transacations and has no configuration
required. SQLite adds powerful data storage to mobile and embedded apps without a large footprint.
Creating and connecting to a database
First import android.databse.sqlite.SQLiteDatabase into your application. Then use the
openOrCreateDatabase() method to create or connect to a database. Create a new project in Eclipse called
TestingData and select the API version of your choice. Use the package name higherpass.TestingData with an
activity TestingData and click finish.
package higherpass.TestingData;
import android.app.Activity;
import android.os.Bundle;
import android.database.sqlite.SQLiteDatabase;
public class TestingData extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SQLiteDatabase db;
db = openOrCreateDatabase(
"TestingData.db"
, SQLiteDatabase.CREATE_IF_NECESSARY
, null
);
}
}
Add the android.database.sqlite.SQLiteDatabase to the standard imports from the new project. After the
standard layout setup initialize a SQLiteDatabase variable to hold the database instance. Next use the
openOrCreateDatabase() method to open the database. The openOrCreateDatabase() method expects the
database file first, followed by the permissions to open the database with, and an optional cursor factory
builder.
Where does Android store SQLite databases?
Android stores SQLite databases in /data/data/[application package name]/databases.
sqlite3 from adb shell
bash-3.1$ /usr/local/android-sdk-linux/tools/adb devices
List of devices attached
emulator-5554 device
bash-3.1$ /usr/local/android-sdk-linux/tools/adb -s emulator-5554 shell
A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
3. # ls /data/data/higherpass.TestingData/databases
TestingData.db
# sqlite3 /data/data/higherpass.TestingData/databases/TestingData.db
SQLite version 3.5.9
Enter ".help" for instructions
sqlite> .tables
android_metadata tbl_countries tbl_states
The Google Android SDK comes with a utility adb. The adb tool can be used to browse and modify the
filesystem of attached emulators and physical devices. This example is a bit ahead of where we are as we
haven't created the databases yet.
Setting database properties
There are a few database properties that should be set after connecting to the database. Use the setVersion(),
setLocale(), and setLockingEnabled() methods to set these properties. These will be demonstrated in the
creating tables example.
Creating Tables
Tables are created by executing statements on the database. The queries should be executed with the execSQL()
statement.
package higherpass.TestingData;
import java.util.Locale;
import android.app.Activity;
import android.os.Bundle;
import android.database.sqlite.SQLiteDatabase;
public class TestingData extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SQLiteDatabase db;
db = openOrCreateDatabase(
"TestingData.db"
, SQLiteDatabase.CREATE_IF_NECESSARY
, null
);
db.setVersion(1);
db.setLocale(Locale.getDefault());
db.setLockingEnabled(true);
final String CREATE_TABLE_COUNTRIES =
"CREATE TABLE tbl_countries ("
+ "id INTEGER PRIMARY KEY AUTOINCREMENT,"
+ "country_name TEXT);";
final String CREATE_TABLE_STATES =
"CREATE TABLE tbl_states ("
+ "id INTEGER PRIMARY KEY AUTOINCREMENT,"
A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
4. + "state_name TEXT,"
+ "country_id INTEGER NOT NULL CONSTRAINT "
+ "contry_id REFERENCES tbl_contries(id) "
+ "ON DELETE CASCADE);";
db.execSQL(CREATE_TABLE_COUNTRIES);
db.execSQL(CREATE_TABLE_STATES);
final String CREATE_TRIGGER_STATES =
"CREATE TRIGGER fk_insert_state BEFORE "
+ "INSERT on tbl_states"
+ "FOR EACH ROW "
+ "BEGIN "
+ "SELECT RAISE(ROLLBACK, 'insert on table "
+ ""tbl_states" voilates foreign key constraint "
+ ""fk_insert_state"') WHERE (SELECT id FROM "
+ "tbl_countries WHERE id = NEW.country_id) IS NULL; "
+ "END;";
db.execSQL(CREATE_TRIGGER_STATES);
}
}
As before open the database with openOrCreateDatabase(). Now configure the database connection with
setVersion to set the database version. The setLocale method sets the default locale for the database and
setLockingEnabled enables locking on the database. Next we setup final String variables to hold the SQLite
table creation statements and execute them with execSQL.
Additionally we manually have to create triggers to handle the foreign key relationships between the table. In a
production application there would also need to be foreign key triggers to handle row updates and deletes. The
foreign key triggers are executed with execSQL just like the table creation.
Inserting records
Android comes with a series of classes that simplify database usage. Use a ContentValues instance to create a
series of table field to data matchings that will be passed into an insert() method. Android has created similar
methods for updating and deleting records.
ContentValues values = new ContentValues();
values.put("country_name", "US");
long countryId = db.insert("tbl_countries", null, values);
ContentValues stateValues = new ContentValues();
stateValues.put("state_name", "Texas");
stateValues.put("country_id", Long.toString(countryId));
try {
db.insertOrThrow("tbl_states", null, stateValues);
} catch (Exception e) {
//catch code
}
Append this code to the previous example. First create a ContentValues object to store the data to insert and use
the put method to load the data. Then use the insert() method to perform the insert query into SQLite. The
insert() function expects three parameters, the table name, null, and the ContentValues pairs. Also a long is
returned by the insert() function. This long will hold the primary key of the inserted row.
A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
5. Next we create a new ContentValues pair for the state and perform a second insert using the insertOrThrow()
method. Using insertOrThrow() will throw an exception if the insert isn't successful and must be surrounded by
a try/catch block. You'll notice that currently the application dies with an unhandled exception because the
tables we're trying to create already exist. Go back into the adb shell and attach to the SQLite database for the
application and drop the tables.
sqlite> drop table tbl_countries;
sqlite> drop table tbl_states;
Updating data
Updating records is handled with the update() method. The update() function supports WHERE syntax similar
to other SQL engines. The update() method expects the table name, a ContentValues instance similar to insert
with the fields to update. Also allowed are optional WHERE syntax, add a String containing the WHERE
statement as parameter 3. Use the ? to designate an argument replacement in the WHERE clause with the
replacements passed as an array in parameter 4 to update.
ContentValues updateCountry = new ContentValues();
updateCountry.put("country_name", "United States");
db.update("tbl_countries", updateCountry, "id=?", new String[]
{Long.toString(countryId)});
First remove the table create statements from the code. We don't need to keep creating and dropping tables.
Now create a new ContentValues instance, updateCountry, to hold the data to be updated. Then use the
update() method to update the table. The where clause in parameter 3 uses replacement of the ? with the values
stored in parameter 4. If multiple ? existed in the where statement they would be replaced in order by the values
of the array.
From the adb shell attach to the database and execute select * FROM tbl_countries; inside sqlite3.
bash-3.1$ /usr/local/android-sdk-linux/tools/adb -s emulator-5554 shell
# sqlite3 /data/data/higherpass.TestingData/databases/TestingData.db
SQLite version 3.5.9
Enter ".help" for instructions
sqlite> select * FROM tbl_countries;
1|United States
Deleting data
Once data is no longer needed it can be removed from the database with the delete() method. The delete()
method expects 3 parameters, the database name, a WHERE clause, and an argument array for the WHERE
clause. To delete all records from a table pass null for the WHERE clause and WHERE clause argument array.
db.delete("tbl_states", "id=?", new String[] {Long.toString(countryId)});
Simply call the delete() method to remove records from the SQLite database. The delete method expects, the
table name, and optionally a where clause and where clause argument replacement arrays as parameters. The
where clause and argument replacement array work just as with update where ? is replaced by the values in the
array.
A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
6. Retrieving data
Retrieving data from SQLite databases in Android is done using Cursors. The Android SQLite query method
returns a Cursor object containing the results of the query. To use Cursors android.database.Cursor must be
imported.
About Cursors
Cursors store query result records in rows and grant many methods to access and iterate through the records.
Cursors should be closed when no longer used, and will be deactivated with a call to Cursor.deactivate() when
the application pauses or exists. On resume the Cursor.requery() statement is executed to re-enable the Cursor
with fresh data. These functions can be managed by the parent Activity by calling startManagingCursor().
package higherpass.TestingData;
import java.util.Locale;
import android.app.Activity;
import android.os.Bundle;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
public class TestingData extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SQLiteDatabase db;
db = openOrCreateDatabase(
"TestingData.db"
, SQLiteDatabase.CREATE_IF_NECESSARY
, null
);
db.setVersion(1);
db.setLocale(Locale.getDefault());
db.setLockingEnabled(true);
Cursor cur = db.query("tbl_countries",
null, null, null, null, null, null);
cur.close();
}
}
Open the database as before. The query performed will return all records from the table tbl_countries. Next
we'll look at how to access the data returned.
Iterating through records
The Cursor class provides a couple of simple methods to allow iterating through Cursor data easily. Use
moveToFirst() to position the Cursor pointer at the first record then use the moveToNext() function to iterate
A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
7. through the records. The isAfterLast() method performs a check to see if the cursor is pointed after the last
record. When looping through records break the loop when this becomes false.
First add the following attribute to the TextView element in the main layout. The main layout is the xml file
located at res/layouts/main.xml. We need to give this TextView element an ID that we can reference to update
the view.
android:id="@+id/hello"
Java code to iterate through entries in a cursor:
package higherpass.TestingData;
import java.util.Locale;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
public class TestingData extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView view = (TextView) findViewById(R.id.hello);
SQLiteDatabase db;
db = openOrCreateDatabase(
"TestingData.db"
, SQLiteDatabase.CREATE_IF_NECESSARY
, null
);
db.setVersion(1);
db.setLocale(Locale.getDefault());
db.setLockingEnabled(true);
Cursor cur = db.query("tbl_countries",
null, null, null, null, null, null);
cur.moveToFirst();
while (cur.isAfterLast() == false) {
view.append("n" + cur.getString(1));
cur.moveToNext();
}
cur.close();
}
}
This code simply creates a cursor querying all the records of the table tbl_countries. The moveToFirst() method
is used to position the cursor pointer at the beginning of the data set. Then loop through the records in the
cursor. The method isAfterLast() returns a boolean if the pointer is past the last record in the cursor. Use the
moveToNext() method to traverse through the records in the cursor.
A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
8. Retrieving a specific record
The cursor also allows direct access to specific records.
Cursor cur = db.query("tbl_countries",
null, null, null, null, null, null);
cur.moveToPosition(0);
view.append("n" + cur.getString(1));
cur.close();
Transactions
SQLite also supports transactions when you need to perform a series of queries that either all complete or all
fail. When a SQLite transaction fails an exception will be thrown. The transaction methods are all part of the
database object. Start a transaction by calling the beginTransaction() method. Perform the queries and then call
the setTransactionSuccessful() when you wish to commit the transaction. Once the transaction is complete call
the endTransaction() function.
db.beginTransaction();
Cursor cur = null;
try {
cur = db.query("tbl_countries",
null, null, null, null, null, null);
cur.moveToPosition(0);
ContentValues values = new ContentValues();
values.put("state_name", "Georgia");
values.put("country_id", cur.getString(0));
long stateId = db.insert("tbl_states", null, values);
db.setTransactionSuccessful();
view.append("n" + Long.toString(stateId));
} catch (Exception e) {
Log.e("Error in transaction", e.toString());
} finally {
db.endTransaction();
cur.close();
}
Start off with a call to beginTransaction() to tell SQLite to perform the queries in transaction mode. Initiate a
try/catch block to handle exceptions thrown by a transaction failure. Perform the queries and then call
setTransactionSuccessful() to tell SQLite that our transaction is complete. If an error isn't thrown then
endTransaction() can be called to commit the transaction. Finally close the cursor when we're finished with it.
Built in android databases
The Android Operating-System provides several built-in databases to store and manage core phone application
data. Before external applications may access some of these data sources access must be granted in the
AndroidManifest.xml file in the root of the project. Some of the data applications can access are the
bookmarks, media player data, call log, and contact data. Contact data not covered due to changes in the API
between 1.x and 2.0 version of Android. See the Android Working With Contacts Tutorial. Android provides
built in variables to make working with the internal SQLite databases easy.
A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
9. Access permissions
Before a program accesses any of the internal Android databases the application must be granted access. This
access is granted in the AndroidManifest.xml file. Before the application is installed from the market the user
will be prompted to allow the program to access this data.
<uses-permission
android:name="com.android.browser.permission.READ_HISTORY_BOOKMARKS" />
<uses-permission
android:name="com.android.broswer.permission.WRITE_HISTORY_BOOKMARKS" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
These are some sample uses-permission statements to grant access to internal Android databases. These are
normally placed below the uses-sdk statement in the AndroidManifest.xml file. The first 2 grant read and write
access to the browser history and bookmarks. The third grants read access to the contacts. We'll need to grant
READ access to the bookmarks and contacts for the rest of the code samples to work.
Managed Query
Managed queries delegate control of the Cursor to the parent activity automatically. This is handy as it allows
the activity to control when to destroy and recreate the Cursor as the application changes state.
package higherpass.TestingData;
import android.app.Activity;
import android.os.Bundle;
import android.provider.Browser;
import android.widget.TextView;
import android.database.Cursor;
public class TestingData extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView view = (TextView) findViewById(R.id.hello);
Cursor mCur = managedQuery(android.provider.Browser.BOOKMARKS_URI,
null, null, null, null
);
mCur.moveToFirst();
int index = mCur.getColumnIndex(Browser.BookmarkColumns.TITLE);
while (mCur.isAfterLast() == false) {
view.append("n" + mCur.getString(index));
mCur.moveToNext();
}
}
}
The managed query functions very similar to the query function we used before. When accessing Android built
in databases you should reference them by calling the associated SDK variable containing the correct database
URI. In this case the browser bookmarks are being accessed by pointing the managedQuery() statement at
android.provider.Browser.BOOKMARKS_URI. We left the rest of the parameters null to pull all results from
the table. Then we iterate through the cursor records. Each time through the loop we append the title of the
A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
10. bookmark to the TextView element. If you know the name of a column, but not it's index in the results use the
getColumnIndex() method to get the correct index. To get the value of a field use the getString() method
passing the index of the field to return.
Bookmarks
The first Android database we're going to explore is the browser bookmarks. When accessing the internal
Android databases use the managedQuery() method. Android includes some helper variables in
Browser.BookmarkColumns to designate column names. They are Browser.BookmarkColumns.TITLE,
BOOKMARK, FAVICON, CREATED, URL, DATE, VISITS. These contain the table column names for the
bookmarks SQLite table.
package higherpass.TestingData;
import android.app.Activity;
import android.os.Bundle;
import android.provider.Browser;
import android.widget.TextView;
import android.database.Cursor;
public class TestingData extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView view = (TextView) findViewById(R.id.hello);
String[] projection = new String[] {
Browser.BookmarkColumns.TITLE
, Browser.BookmarkColumns.URL
};
Cursor mCur = managedQuery(android.provider.Browser.BOOKMARKS_URI,
projection, null, null, null
);
mCur.moveToFirst();
int titleIdx = mCur.getColumnIndex(Browser.BookmarkColumns.TITLE);
int urlIdx = mCur.getColumnIndex(Browser.BookmarkColumns.URL);
while (mCur.isAfterLast() == false) {
view.append("n" + mCur.getString(titleIdx));
view.append("n" + mCur.getString(urlIdx));
mCur.moveToNext();
}
}
}
This code works as before, with the addition of limiting return columns with a projection. The projection is a
string array that holds a list of the columns to return. In this example we limited the columns to the bookmark
title (Browser.BookmarkColumns.TITLE) and URL (Browser.BookmarkColumns.URL). The projection array
is then passed into managedQuery as the second parameter.
A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
11. Media Player
The Android Media-player also uses SQLite to store the media information. Use this database to find media
stored on the device. Available fields are DATE_ADDED, DATE_MODIFIED, DISPLAY_NAME,
MIME_TYPE, SIZE, and TITLE.
package higherpass.TestingData;
import android.app.Activity;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.MediaStore.Audio.Media;
import android.widget.TextView;
import android.database.Cursor;
public class TestingData extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView view = (TextView) findViewById(R.id.hello);
String[] projection = new String[] {
MediaStore.MediaColumns.DISPLAY_NAME
, MediaStore.MediaColumns.DATE_ADDED
, MediaStore.MediaColumns.MIME_TYPE
};
Cursor mCur = managedQuery(Media.EXTERNAL_CONTENT_URI,
projection, null, null, null
);
mCur.moveToFirst();
while (mCur.isAfterLast() == false) {
for (int i=0; i<mCur.getColumnCount(); i++) {
view.append("n" + mCur.getString(i));
}
mCur.moveToNext();
}
}
}
The only differences here is that we use getColumnCount() to determine the number of columns in the returned
records and loop through displaying each column.
Call Log
If granted permission Android applications can access the call log. The call log is accessed like other
datastores.
package higherpass.TestingData;
import android.app.Activity;
import android.os.Bundle;
import android.provider.CallLog;
import android.provider.CallLog.Calls;
A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
12. import android.widget.TextView;
import android.database.Cursor;
public class TestingData extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView view = (TextView) findViewById(R.id.hello);
String[] projection = new String[] {
Calls.DATE
, Calls.NUMBER
, Calls.DURATION
};
Cursor mCur = managedQuery(CallLog.Calls.CONTENT_URI,
projection, Calls.DURATION +"<?",
new String[] {"60"},
Calls.DURATION + " ASC");
mCur.moveToFirst();
while (mCur.isAfterLast() == false) {
for (int i=0; i<mCur.getColumnCount(); i++) {
view.append("n" + mCur.getString(i));
}
mCur.moveToNext();
}
}
}
This final example introduces the rest of the managedQuery() parameters. After the projection we pass a
WHERE clause in the same way they were crafted in the update and delete sections earlier. After the where
clause comes the array of replacement arguments. Finally we pass in an order by clause to tell SQLite how to
sort the results. This query only retrieves records for phone calls lasting less than 60 seconds and sorts them by
duration ascending.
A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi