The document discusses SQLiteOpenHelper class and how it helps in performing database operations like creating, opening and upgrading a SQLite database. It also describes how to open a database using getWritableDatabase() or getReadableDatabase() methods, insert data into tables using ContentValues and insert() method, implement content providers to allow external access to the database and methods like query(), insert(), update() etc to perform database operations through content providers.
2. SQLiteOpenHelper Class
• Is one of the abstract classes that allows a user to access a
database in READ mode or WRITE mode.
• Helps in performing the manipulation of data available in
the Db.
• Operation includes creating, opening and upgrading.
• Uses methods like getWritableDatabase() to write ,
getReadableDatabase() to read, close() to close the
database by running the object of SQLite database.
• insert() method inserting no. of rows in database table,
query() method executing various SQLite queries.
3. How a database is opened
• Can be accessed getWritableDatabase or
getReadableDatabase of SQLiteOpenHelper
class.
• onCreate handler is triggered if the searched
database doesn’t exists.
• Sometimes getWritableDatabase might not
work for reasons like permission, disk space.
In such case we can use getReadableDatabase
method.
• Sample in next slide
4. Code
• DBOpenHelper hp = new DBOpenHelper(e,
DBOpenHelper.name, null, DBOpenHelper.v);
• SQLiteDatabase db;
• try
• {
• db = DBOpenHelper.getWritableDatabase();
• }
• catch (SQLiteException e)
• {
• db = DBOpenHelper.getReadableDatabase();
• }
5. Method to insert data into table
• New row in database can be created using ContentValues
object (add column name and value)
• insert() used for inserting data into table.
• Accepts 3 arguments namely table name, null column hack
and name value pairs.
• The argument table indicates name of the table,
• null column hack prevents an error when inserting a new
record without specifying field value pairs and
• name value pairs are the actual data that need to be
inserted in a table.
• db.insert(DBOpenHelper.DATABASE_NAME, null, values);
6. Content Provider
• Content providers let you centralize content 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.
7. 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>
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.mrecw.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.
8. How content provider is registered.
• The content provider need to be registered in the app manifest.
A provider tag is used for this purpose.
• This tag accompanies name attribute that represents providers
class name and authorities tag.
• The latter tag is used to define the base URI of providers
authority.
• Authority of a content provider is used by content
resolver in form of address to find the required data.
• com.<CompanyName>.provider.<AppliocationName>
• The provider tag is below with XML format
• <provider android :name=“.MyContentProvider”
android:authorities =“com.paad.skeletondbprovider”/>
9. Create Content Provider
• This involves number of simple steps to create your own 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.
• Third 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.
• Fourth 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.
10. 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
11. Implementing the Content Provider query() Method
• When a content provider is called upon to return data, the query() method of
the provider class will be called.
• When called, this method is passed some or all of the following arguments:
• URI – The URI specifying the data source on which the query is to be
performed. This can take the form of a general query with multiple results, or
a specific query targeting the ID of a single table row.
• Projection – A row within a database table can comprise multiple columns of
data. In the case of this application,
• for example, these correspond to the ID, product name and product
quantity. The projection argument is simply a String array containing the name
for each of the columns that is to be returned in the result data set.
• Selection – The “where” element of the selection to be performed as part of
the query. This argument controls which rows are selected from the specified
database.
• For example, if the query was required to select only products named “Cat
Food” then the selection string passed to the query() method would read
productname = “Cat Food”.
• Selection Args – Any additional arguments that need to be passed to the SQL
query operation to perform the selection.
• ‘Sort Order' – The sort order for the selected rows.
12. • When called, the query() method is required to
perform the following operations:
• Use the sUriMatcher to identify the Uri type.
• Throw an exception if the URI is not valid.
• Construct a SQL query based on the criteria passed to
the method. For convenience, the SQLiteQueryBuilder
class can be used in construction of the query.
• Execute the query operation on the database.
• Notify the content resolver of the operation.
• Return a Cursor object containing the results of the
query.
14. insert()
• This method now needs to be modified to perform the
following tasks:
• Use the UriMatcher to identify the URI type.
• Throw an exception if the URI is not valid.
• Obtain a reference to a writable instance of the
underlying SQLite database.
• Perform a SQL insert operation to insert the data into
the database table.
• Notify the corresponding content resolver that the
database has been modified.
• Return the URI of the newly added table row.
15. Inserting content into content provider
• When a client application or activity requests that data be
inserted into the underlying database, the insert() method
of the content provider class will be called.
• At this point, however, all that exists in the
ContentProvider.java file of the project is a stub method,
which reads as follows:
• @Override public Uri insert(Uri arg0, ContentValues arg1) {
• // TODO Auto-generated method stub return null;
• }
16. • @Override
• public Uri insert(Uri uri, ContentValues values) {
• int uriType = sURIMatcher.match(uri);
• SQLiteDatabase sqlDB = myDB.getWritableDatabase();
• long id = 0;
• switch (uriType) {
• case PRODUCTS:
• id = sqlDB.insert(MyDBHandler.TABLE_PRODUCTS, null, values);
• break;
• default:
• throw new IllegalArgumentException("Unknown URI: " + uri);
• }
• getContext().getContentResolver().notifyChange(uri, null);
• return Uri.parse(PRODUCTS_TABLE + "/" + id);
• }
17. Implementing the Content Provider update() Method
• The update() method of the content provider is called
when changes are being requested to existing database
table rows. The method is passed a URI, the new values
in the form of a ContentValues object and the usual
selection argument strings.
• When called, the update() method would typically
perform the following steps:
• Use the sUriMatcher to identify the URI type.
• Throw an exception if the URI is not valid.
• Obtain a reference to a writable instance of the
underlying SQLite database.
• Notify the content resolver of the database change.
• Return a count of the number of rows that were changed
as a result of the update operation.