0% found this document useful (0 votes)
1 views12 pages

Unit 5 (Android) 1

This document covers the fundamentals of Android programming related to databases and content providers, focusing on SQLite, ContentValues, and Cursors. It explains how to create and manage SQLite databases, perform CRUD operations, and implement content providers for data sharing between applications. Key concepts include the use of SQLiteOpenHelper, query methods, and the structure of URIs for content providers.

Uploaded by

deveshvpatil20
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views12 pages

Unit 5 (Android) 1

This document covers the fundamentals of Android programming related to databases and content providers, focusing on SQLite, ContentValues, and Cursors. It explains how to create and manage SQLite databases, perform CRUD operations, and implement content providers for data sharing between applications. Key concepts include the use of SQLiteOpenHelper, query methods, and the structure of URIs for content providers.

Uploaded by

deveshvpatil20
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Android Programming

Unit-5 Database and content provider


Syllabus:
• SQLite

• Content values and cursors

• Creating SQLite databases


• Querying a database

• Adding, Updating, Removing rows

• Creating content Providers

• Implement content provides queries and its usage

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.

• It is embedded in android bydefault. So, there is no need to perform any database


setup or administration task.

• 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 provides the functionality to use the SQLite database.

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.

Prof. Rahul Khandarkar 1


Android Programming

• Constructors of SQLiteOpenHelper class


• There are two constructors of SQLiteOpenHelper class.

• There are two constructors of SQLiteOpenHelper class.

• SQLiteOpenHelper(Context context, String name,


SQLiteDatabase.CursorFactory factory, int version)
• It creates an object for creating, opening and managing the database.

• SQLiteOpenHelper(Context context, String name,


SQLiteDatabase.CursorFactory factory, int version, DatabaseErrorHandler
errorHandler):
• It creates an object for creating, opening and managing the database. It specifies the
error handler.

Methods of SQLiteOpenHelper class:

• public abstract void onCreate(SQLiteDatabase db): called only once when


database is created for the first time.

• public abstract void onUpgrade(SQLiteDatabase db, int oldVersion, int


newVersion):called when database needs to be upgraded.

• public synchronized void close (): closes the database object.

• public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion):


called when database needs to be downgraded.

Content values and cursors:


• ContentValues objects are used to insert new rows into database tables (and Content
Providers). Each Content Values object represents a single row, as a map of column
names to values.

Prof. Rahul Khandarkar 2


Android Programming

• 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.

• moveToPrevious Moves the cursor to the previous row.

• getCount Returns the number of rows in the result set.

• 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.

• getPosition Returns the current cursor position.

• Android provides a mechanism to manage Cursor resources within your Activities.

• 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.

Creating SQLite databases:


• In order to create a database you just need to call this method openOrCreateDatabase
with your database name and mode as a parameter.

Prof. Rahul Khandarkar 3


Android Programming

• It returns an instance of SQLite database which you have to receive in your own
object.

• SQLiteDatabase mydatabase = openOrCreateDatabase("your database


name",MODE_PRIVATE,null);

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.

Cursor resultSet = mydatbase.rawQuery("Select * from Student",null);


resultSet.moveToFirst();
String username = resultSet.getString(0);

String password = resultSet.getString(1);

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.

• getColumnIndex(String columnName) This method returns the index number of a


column by specifying the name of the column.

Prof. Rahul Khandarkar 4


Android Programming

• getColumnName(int columnIndex) This method returns the name of the column by


specifying the index of the column.

• 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.

• insert() function has three parameters like

public long insert (String tableName,String nullColumnHack,ContentValues


values)

• where tableName is name of table in which data to be inserted.

• 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.

Prof. Rahul Khandarkar 5


Android Programming

• 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[])

• Update function is available in SQLiteDatabase class it looks as follows:

public int update(String tableName,ContentValues contentValues,


String whereClause,String[] whereArgs)

• Update function will return number of rows affected if success, 0 otherwise.

• Here is simple use of update:

• //Item is a class representing any item with id, name and description

public void updateItem(Item item) {

SQLiteDatabase db = getWritableDatabase();

ContentValues contentValues = new

ContentValues(); contentValues.put("id", item.id);

Prof. Rahul Khandarkar 6


Android Programming

contentValues.put("name", item.name);
contentValues.put("description", item.description);

String whereClause = "id=?";

String whereArgs[] = {item.id.toString()};

db.update("Items", contentValues, whereClause, whereArgs); }

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.

public int delete(String tableName,String whereClause,String [] whereArgs)

• function has three parameters these are totally similar to update function’s parameters
and are used in same way as in update function.

• Here is simple use of delete:

public void deleteItem(Item item) {


SQLiteDatabase db = getWritableDatabase();

String whereClause = "id=?";


String whereArgs[] = {item.id.toString()};

db.delete("Items", whereClause, whereArgs);

Prof. Rahul Khandarkar 7


Android Programming

• 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.

Creating content Providers:


• Content providers let you centralize content in one place and have many different
applications access it as needed. A content provider behaves very much like a database
where you can query it, edit its content, as well as add or delete content using insert(),
update(), delete(), and query() methods. In most cases this data is stored in an SQlite
database.

• A content provider is implemented as a subclass of ContentProvider class and must


implement a standard set of APIs that enable other applications to perform
transactions.

public class My Application extends ContentProvider { }

Content URIs:

Prof. Rahul Khandarkar 8


Android Programming

• 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>

Sr.No Part & Description


1 Prefix:
This is always set to content://
2 Authority:
This specifies the name of the content provider, for
example contacts, browser etc. For third-party content providers, this could be
the fully qualified name, such as com.raisoni.statusprovider
3 data_type:
This indicates the type of data that this particular provider provides. For
example, if you are getting all the contacts from the Contacts content provider,
then the data path would be people and URI would look like
thiscontent://contacts/people
4 Id:
This specifies the specific record requested. For example, if you are looking for
contact number 5 in the Contacts content provider then URI would look like
this content://contacts/people/5.

Create Content Provider:


• First of all you need to create a Content Provider class that extends the
ContentProviderbaseclass.

• 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.

Prof. Rahul Khandarkar 9


Android Programming

• 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 –

• onCreate() -This method is called when the provider is started.

• 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.

Implement content provider’s queries and its usage:


• Content providers can help an application manage access to data stored by itself,
stored by other apps, and provide a way to share data with other apps.
• They encapsulate the data, and provide mechanisms for defining data security.

Prof. Rahul Khandarkar 10


Android Programming

• 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.

• Use content providers if you plan to share data.

• 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

Prof. Rahul Khandarkar 11


Android Programming

Prof. Rahul Khandarkar 12

You might also like