Unit 5 (Android) 1
Unit 5 (Android) 1
SQLite
• SQLite is an open-source relational database i.e. used to perform database
operations on android devices such as storing, manipulating or retrieving persistent
data from the database.
• Here, we are going to see the example of sqlite to store and fetch the data. Data is
displayed in the logcat. For displaying data on the spinner or listview, move to the
next page.
SQLiteOpenHelper class
• The android.database.sqlite.SQLiteOpenHelper class is used for database creation
and version management. For performing any database operation, you have to provide
the implementation of onCreate() and onUpgrade() methods of SQLiteOpenHelper
class.
• Queries in Android are returned as Cursor objects. Rather than extracting and
returning a copy of the result values, Cursors act as pointers to a subset of the
underlying data. Cursors are a managed way of controlling your position (row) in the
result set of a database query.
• The Cursor class includes several functions to navigate query results including, but
not limited to, the following:
• moveToFirst Moves the cursor to the first row in the query result.
• moveToNext Moves the cursor to the next row.
• getColumnIndexOrThrow Returns an index for the column with the specified name
(throwing an exception if no column exists with that name).
• getColumnName Returns the name of the specified column index.
• getColumnNames Returns a String array of all the column names in the current
cursor.
• moveToPosition Moves the cursor to the specified row.
• The startManagingCursor method integrates the Cursor’s lifetime into the parent
Activity’s lifetime management.
• When you’ve finished with the Cursor, call stopManagingCursor to do just that.
Later in this chapter, you’ll learn how to query a database and how to extract specific
row/column values from the resulting Cursor objects.
• It returns an instance of SQLite database which you have to receive in your own
object.
Database – Insertion:
• we can create table or insert data into table using execSQL method defined in
SQLiteDatabase class.
mydatabase.execSQL("CREATE TABLE IF NOT EXISTS Student(Username
VARCHAR,Password VARCHAR);"); mydatabase.execSQL("INSERT INTO Student
VALUES('admin','admin');");
• This will insert some values into our table in our database.
Database – Fetching:
• We can retrieve anything from database using an object of the Cursor class.
• We will call a method of this class called rawQuery and it will return a resultset with
the cursor pointing to the table. We can move the cursor forward and retrieve the data.
There are other functions available in the Cursor class that allows us to effectively retrieve
the data:
• getColumnCount() This method return the total number of columns of the table.
• getColumnNames() This method returns the array of all the column names of the
table.
• getCount() This method returns the total number of rows in the cursor.
• getPosition() This method returns the current position of the cursor in the table.
• isClosed() This method returns true if the cursor is closed and return false otherwise
Querying a database:
• Android provides different ways to store data locally so using SQLite is one the way
to store data.
• SQLite is a structure query base database; hence we can say it’s a relation database.
• Android os has its own implementation to perform CRUD (Create, Read, Update,
Delete) operations, so Android provides set of classes available in android.database
and android.database.sqlite packages.
Insert:
• To perform insert operation using parameterized query we have to call insert function
available in SQLiteDatabase class.
• NullColumnHack may be passed null, it require table column value in case we don’t
put column name in ContentValues object so a null value must be inserted for that
particular column, values are those values that needs to be inserted.
• ContentValues is a key-pair based object which accepts all primitive type values so
whenever data is being put in ContentValues object it should be put again table
column name as key and data as value.
• insert function will return a long value i.e number of inserted row if successfully
inserted, – 1 otherwise.
Update:
• Update function is quite similar to insert but it requires two additional parameters, it
doesn’t required nullColumnHack.
• It has total four parameters two are similar to insert function that is tableName and
contentValues.
• Another two are whereClause(String) and whereArgs(String[])
• //Item is a class representing any item with id, name and description
SQLiteDatabase db = getWritableDatabase();
contentValues.put("name", item.name);
contentValues.put("description", item.description);
Delete:
• Similar to insert and update, delete function is available in SQLiteDatabase class,
• So delete is very similar to update function apart from ContentValues object as it’s not
required in delete.
• function has three parameters these are totally similar to update function’s parameters
and are used in same way as in update function.
• Here whereClause is optional, passing null will delete all rows in table. delete function
will return number of affected row if whereClause passed otherwise will return 0.
Content URIs:
• To query a content provider, you specify the query string in the form of a
URI which has following format –
<prefix>://<authority>/<data_type>/<id>
• Second, you need to define your content provider URI address which will be used to
access the content.
• Next you will need to create your own database to keep the content. Usually, Android
uses SQLite database and framework needs to override onCreate() method which will
use SQLite Open Helper method to create or open the provider's database. When your
application is launched, the onCreate() handler of each of its Content Providers is
called on the main application thread.
• Next you will have to implement Content Provider queries to perform different
database specific operations.
• Finally register your Content Provider in your activity file using <provider> tag.
Here is the list of methods which you need to override in Content Provider class to have your
Content Provider working –
• query() - This method receives a request from a client. The result is returned as a
Cursor object.
• insert() - This method inserts a new record into the content provider.
• delete() - This method deletes an existing record from the content provider.
• update() - This method updates an existing record from the content provider.
• getType() – This method returns the MIME type of the data at the given URI.
• Content providers are the standard interface that connects data in one process with
code running in another process.
• Implementing a content provider has many advantages. Most importantly you can
configure a content provider to allow other applications to securely access and modify
your app data as illustrated in figure 1.
• If you don’t plan to share data, you may still use them because they provide a nice
abstraction, but you don’t have to.
• This abstraction allows you to make modifications to your application data storage
implementation without affecting other existing applications that rely on access to
your data.
• In this scenario only your content provider is affected and not the applications that
access it.
• For example, you might swap out a SQLite database for alternative storage as
illustrated in figure 2