You are on page 1of 8

Android Apps Programming

Database Management in 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


directory DATA/data/APP_NAME/databases/FILENAME . The parts of the above
directory are constructed based on the following rules. DATA is the path which
the Environment.getDataDirectory() method returns. APP_NAME is your application
name. FILENAME is the name you specify in your application code for the database.

SQLite architecture

Packages
The android.database package contains all necessary classes for working with
databases. The android.database.sqlite package contains the SQLite specific classes.

SQLiteDatabase
SQLiteDatabase is the base class for working with a SQLite database in Android
and provides methods to open, query, update and close the database. It provides
the execSQL() method, which allows to execute an SQL statement directly.

Using the Code


The SQLiteDatabase class from the android.database.sqlite package and
the Cursor class from the android.database package provide all the functionality

Lecture 11 Database in Android Page 1


Android Apps Programming

required for performing Data Manipulation Language (DML) and query operations on an
SQLite table.

Creating SQLite database and a table in the database:

Syntax:

db=openOrCreateDatabase(<dabasename>, Context.MODE_PRIVATE, null);


db.execSQL("CREATE TABLE IF NOT EXISTS <tablename>(
fieldkey1 fieldtype, fieldkey2 fieldtype, ... ););

Example:

db=openOrCreateDatabase("StudentDB", Context.MODE_PRIVATE, null);


db.execSQL("CREATE TABLE IF NOT EXISTS student(studno VARCHAR,
name VARCHAR,marks VARCHAR);");

openOrCreateDatabase()
It is used to open the database if it exists or create a new one if it does not exist.

The first parameter specifies the name of the database to be opened or created.
The second parameter, Context.MODE_PRIVATE indicates that the database file can
only be accessed by the calling application or all applications sharing the same user ID.
The third parameter is a Cursor factory object which can be left null if not required.

db.execSQL()
it is used to execute any SQL command. Here it is used to create
the student table if it does not already exist in the database.

Example:

db.execSQL("INSERT INTO student VALUES('" + editStudno.getText() + "','" +


editName.getText() + "','" + editMarks.getText() + "');");

db.execSQL("DELETE FROM student WHERE rollno = '" + editStudno.getText()


+ "'");

db.execSQL("UPDATE student SET name='" + editName.getText() + "',marks='" +


editMarks.getText() + "' WHERE studno='" + editStudno.getText() + "'");

Queries can be created via the rawQuery() and query() methods or via
the SQLiteQueryBuilder class .

rawQuery()
It directly accepts an SQL select statement as input.

Lecture 11 Database in Android Page 2


Android Apps Programming

Syntax:
Cursor c = db.rawQuery(Select ....);

Example:
Cursor c=db.rawQuery("SELECT * FROM student WHERE studno='" +
editstudno.getText() + "'", null);
if(c.moveToFirst()) {
editName.setText(c.getString(1));
editMarks.setText(c.getString(2));
}

To view all records, the following code can be used:

Cursor c=db.rawQuery("SELECT * FROM student", null);


if(c.getCount()==0) {
showMessage("Error", "No records found");
return;
}

StringBuffer buffer=new StringBuffer();


while(c.moveToNext()) {
buffer.append("Studno: "+c.getString(0)+"\n");
buffer.append("Name: "+c.getString(1)+"\n");
buffer.append("Marks: "+c.getString(2)+"\n\n");
}

showMessage("Student Details", buffer.toString());


public void showMessage(String title,String message) {
Builder builder=new Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(message);
builder.show();
}

query()
provides a structured interface for specifying the SQL query

Example : return database.query(DATABASE_TABLE, new String[] { KEY_ROWID,


KEY_CATEGORY, KEY_SUMMARY, KEY_DESCRIPTION }, null, null,
null, null, null);

Lecture 11 Database in Android Page 3


Android Apps Programming

Parameters of the query() method

Parameter Comment

String dbName The table name to compile the query against.

String[] A list of which table columns to return. Passing "null"


columnNames will return all columns.

String whereClause Where-clause, i.e. filter for the selection of data, null
will select all data.

String[] You may include ?s in the "whereClause"". These


selectionArgs placeholders will get replaced by the values from the
selectionArgs array.

String[] groupBy A filter declaring how to group rows, null will cause the
rows to not be grouped.

String[] having Filter for the groups, null means no filter.

String[] orderBy Table 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.

There are two methods used to retrieve the database. The getReadableDatabase()
to retrieve read only database and getWriteableDatabase() to retrieve a database that
can be read and write to. The database tables should use the identifier _id for the primary
key of the table. Several Android functions rely on this standard.
Example : Cursor cursor = getReadableDatabase().rawQuery(
"select * from todo where _id = ?", new String[] { id });

Lecture 11 Database in Android Page 4


Android Apps Programming

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 moveToNext() method. The
isAfterLast()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), 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. A Cursor needs to be
closed with the close() method call.

Creating and updating database with SQLiteOpenHelper


The OpenHelper isnt a database itself. But it does create the database for you, and gives
you access to it. To create and upgrade a database in your Android application you create a
subclass of the SQLiteOpenHelper class. 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 the onCreate() method.

Both methods receive an SQLiteDatabase object as parameter which is the Java


representation of the database.

Create a database for the app


Create a new DatabaseHelper class and its Internal SQLiteOpenHelper that extends
SQLiteOpenHelper. Pass the database name and the database version to super.
Make an empty implementation of onCreate and onUpgrade.
private class MyOpenHelper extends SQLiteOpenHelper {
MyOpenHelper(Context context) {
super(context, Databasename, null, Databaseversion);
}

Lecture 11 Database in Android Page 5


Android Apps Programming

public void onCreate(SQLiteDatabase database) {


// Build the database table in here
database.execSQL(create table tblPlayers ( _id integer primary
key playerName text, playerPower integer));
}
public void onUpgrade(SQLiteDatabase database,
int oldVersion, int newVersion) {
// Handle database schema upgrades in here
Database.exexSQL(DROP TABLE IF EXISTS tblPlayers);
onCreate(database);
}
}

public class myDatabaseHelper{


// Put all constants here for referencing database internal values

private MyOpenHelper openHelper;
private SQLiteDatabase database;
}
Instantiate the OpenHelper on the DatabaseHelper
public MyDatabaseHelper(Context context) {
// It cause the database to be created
openHelper = new MyOpenHelper(context);
database = openHelper.getWritableDatabase();
}

When the openHelper is instantiated, the database file was ctreated and saved
to your applications persistent storage. View the file by opening the Android File
Explorer.
Click Window Show View Other,
expand the Android folder and select File Explorer
Navigate to project folder and you will see the database file.

Create method for inserting/updating records on the Table

public void addrecord(String playerName, int power){


database.execSQL(Insert into tblPlayer values ( + pname + , + power +)); }

Android provides a number of utilities to avoid difficulties in SQL Statements. One


of the utilities is the insert method on SQLiteDatabase. Insert takes a parameter called
ContentValues consisting of a set of key / value pairs. The key represents the table
column identifier and the value represents the content for the table record in this
column. ContentValues can be used for inserts and updates of database entries.

Lecture 11 Database in Android Page 6


Android Apps Programming

public void addRecord(String pName, int power) {


ContentValues contentValues = new ContentValues();
contentValues.put(playerName,pName);
contentValues.put(playerPower, power);
database.insert(tblPlayers, null, contentValues);
}

public Cursor getAllRecords(){


return database.rawQuery(Select * from + TBL_NAME,null);
}

Add databaseHelper to the Activity


MyDatabaseHelper dbHelper = new MyDatabaseHelper(this);

Access the database by calling its method


Example: dbHelper.addRecord(RAC,100);

Iterating the cursor


Example: Cursor cursor = helper.getAllRecords(){
if (cursor.moveFirst()){
do {
String pName = cursor.getString(1);
int power = cursor.getInt(2);
...
}
if (!cursor.isClosed()) {
cursor.close();
}

Using CursorAdapter
The Android SDK includes a special adapter to easily get a Cursor working with
a ListView called CursorAdapter. Youll be able to instantiate a CursorAdapter, passing
in a Cursor. The CursorAdapter then acts as a facilitator between the ListView and the
Cursor to render the contents of the Cursor. CursorAdapter implementations override
two separate method. One method, newView, inflates the view. The other method,
bindView, is responsible for populating the view with the selected data.

public class MyListAdapter extends CursorAdapter {


public MyListAdapter (Context context, Cursor cursor) {
super(context, cursor);
}

public void bindView (View view, Context context, Cursor cursor) {


//fields are retrieved and populated with data
TextView tvname = (TextView) view.findViewById(R.id.tvName);
tvname.setText(cursor.getString(cursor.getColumnIndex(1));

Lecture 11 Database in Android Page 7


Android Apps Programming

TextView tvpower = (TextView) view.findViewById(R.id.tvPower);


tvpower.setText(String.valueOf(cursor.getInt(
cursor.getColumnIndex(2)));
}

public View newView(Context context, Cursor cursor,


ViewGroup parent) {
//LayoutInflater is retrieved and the layout is inflated and returned
Layout inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.list1,parent,false);
return view;
}
}

Update the activity to use the adapter

MyListAdapter adapter = new new MyListAdapter(this,


databasehelper.getAllRecords());
Listview.setAdapter(adapter);

Performance

Changes in SQLite are ACID (atomic, consistent, isolated, durable). This means
that every update, insert and delete operation is ACID. Unfortunately this requires some
overhead in the database processing therefore you should wrap updates in the SQLite
database in an transaction and commit this transaction after several operations. This
can significantly improve performance.

More information about SQLite can be found on the SQLite ebsite:


http://www.sqlite.org.

Lecture 11 Database in Android Page 8

You might also like