11 - Database in Android
11 - Database 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 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.
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.
required for performing Data Manipulation Language (DML) and query operations on an
SQLite table.
Syntax:
Example:
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:
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.
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));
}
query()
provides a structured interface for specifying the SQL query
Parameter Comment
String whereClause Where-clause, i.e. filter for the selection of data, null
will select all data.
String[] groupBy A filter declaring how to group rows, null will cause the
rows to not be grouped.
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 });
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.
onCreate() - is called by the framework, if the database is accessed but not yet
created.
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.
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.
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.