9892124323 | Book Call Girls in Juhu and escort services 24x7
Android Database
1. Mobile Application with Database
Dr.P.Karthikeyan
Associate Professor
Department of Information Technology
Thiagarajar College of Engineering
Madurai 625 015
2. • SQLite is an open source embedded relational database.
• It is a light weight, file based database used as a Library
for an application.
• SQLite engine is not a standalone process, it coexists
inside the application it serves – within its process
space.
• It is a loosely and dynamically typed database.
• Each SQLite database is private to the application, so it
becomes an integrated part of the application that
creates it.
• SQLite also has a standalone tool to access the
databases, sqlite3.
SQLite Database
3. • Android provides following classes to create and
manage databases:
SQLiteDatabase
SQLiteOpenHelper
• SQLiteOpenHelper class is used to manage creation and
versioning of a database.
• SQLiteDatabase class expose methods to manage a
SQLite database, it provides methods to create, delete,
execute SQL commands, and perform other common
database management tasks.
SQLite Database
4. • To create and open a database, the best option is to
create a subclass of SQLiteOpenHelper.
• The subclass of SQLiteOpenHelper should implement
following methods:
• Constructor (Context context, String databaseName,
SQLiteDatabase.CursorFactory factory, int version)
• onCreate(SQLiteDatabase db) - Called when the
database is created for the first time. This is where
the creation of tables and the initial population of
the tables should happen.
• onUpgrade() - The implementation should use this
method to drop tables, add tables, or do anything
else it needs to upgrade to the new schema version.
SQLiteOpenHelper
5. • onOpen() (Optional) - Called when the database has
been opened. Override method should check
isReadOnly() before updating the database.
• getWritableDatabase() is used to open and return a
database that will be used for reading and writing.
• getReadableDatabase() is used to open and return a
database for reading.
• close() is used to close any open database.
SQLiteOpenHelper
6. It exposes following methods to manage a SQLite
database.
• Create() – To create a memory baked database.
• Insert() – To insert a row into the database.
• Replace() – To replace a row in the database.
• Delete() – To delete rows in a database.
• execSQL() – To execute a single SQL statement.
• query() - Executes a query and returns a Cursor
object over the result set.
SQLiteDatabase
7. • isOpen() – To check whether the database is open or
not.
• isReadOnly() – To check whether database is opened as
read only.
• openDatabse() – Open the database according to
certain flags like OPEN_READONLY,
OPEN_READWRITE, CREATE_IF_NECESSARY, etc.
• openOrCreateDatabase() – Equivalent to
openDatabase() with flag CREATE_IF_NECESSARY.
SQLiteDatabase
8. • To add a new record to the database, setup a map of
key-value pairs in a ContentValues object,
• Key – name of the column
• Value – value for the new record in that column
• Then call SqliteDatabase - insert() by passing tablename
and ContentValues object for inserting a record
ContentValues
SqliteDatabase db;
ContentValues values = new ContentValues();
values.put(Column_Name, Column_Value);
values.put(Name, “Raja”);
db.insert(Table_Name, Null, values);
9. • Cursor provides random read-write access to the result
set returned by a database query.
• Some of its methods are:
• getCount() – Returns the no. of rows in result set
• moveToFirst() – Moves the cursor position to first
row
• moveToLast() – Moves the cursor position to last
row
• moveToNext() – Moves to next row
• moveToPrevious() – Moves to previous row
• moveToPosition(index) – Moves the cursor to an
absolute position
Cursor
10. • getColumnName(index) – Returns column name for
specified index
• getColumnNames() – Returns column names in String
array
• getPosition() – Returns the current position of cursor in
row set
• isFirst() & isLast() – Returns true if cursor is at first and
last row respectively
• isClosed() – Returns true if the cursor is closed
• isNull(index) – Returns true if the column value is null
• get<type> methods – getString(), getInt(), getFloat() etc
Cursor
11. 1. query(arg1 , arg2 , arg3 , arg4 , arg5 , arg6 , arg7,
arg8, arg9 )
• arg1 – Boolean , returns unique values
• arg2 – Database table name
• arg3 – Projection, an array of strings: columns
• arg4 – where clause with wildcard ?
• arg5 – wildcard ? values of where
• arg6 – group by clause
• arg7 – having clause
• arg8 – order of the returned rows (col. name)
• arg9 – limit for the no. of returned rows
2. query(arg1 , arg2 , arg3 , arg4 , arg5 , arg6 , arg7)
Query( ) Methods
12. String where=“_id=4”;
String st=“ “;
Cursor c;
c = db.query(TB_Name, null, where, null , null, null, null);
if(c.moveToFirst())
do
{
st = st +" "+ c.getString(1);
}while(c.moveToNext( ));
//Print st
Example: Cursor with Query
13. Updating and Deleting Records
Updating:
SqliteDatabase db;
ContentValues updatedValues = new ContentValues();
updatedValues.put(Column_Name, Column_Value);
String where = “_id = 3”;
db.update(Table_Name, updatedValues, where, null);
Deleting:
db.delete(Table_Name, where, null);
14. • In Android applications, DATA are private to its own
process. To access DATA from other applications,
Android provides a mechanism called Content
Provider.
• A Content provider is used to make a specific set of the
application's data available to other applications.
• They are the only way to share data across applications.
• Android is shipped with number of content providers
for common data types such as audio, video, images,
personal contact information, and so on.
Content Provider
15. • Content providers expose their data as a simple table
on a database model, where each row is a record and
each column is data of a particular type and meaning.
• Every record includes a numeric _ID field that
uniquely identifies the record within the table.
• A query returns a Cursor object that can move from
record to record and column to column to read the
contents of each field.
Data Model
16. • Each content provider exposes a public URI (wrapped
as a Uri object) that uniquely identifies its data set.
• All URIs for providers begin with the string
"content://".
• While defining a content provider, it's a good idea to
also define a constant for its URI. Android defines
CONTENT_URI constants for all the providers that
come with the platform.
URI
18. • Extend the ContentProvider class to provide access to
the data.
• Set up a system for storing the data. Most content
providers store their data using Android's file storage
methods or SQLite databases. This means
implementing six abstract methods declared in the
ContentProvider class:
• query(), insert(), update(), delete(), getType(),
onCreate()
• Declare the content provider in the manifest file for
your application (AndroidManifest.xml)
Creating Content Provider
19. • To add a new record to a content provider, set up a
map of key-value pairs in a ContentValues object,
key : Name of a column in the content provider
value : desired value for the new record in that column.
• Then call ContentResolver.insert() and pass it the URI
of the provider and the ContentValues map.
• Method returns the full URI of the new record i.e.,
provider's URI with the appended ID for the new
record.
Adding Records
ContentValues values = new ContentValues();
values.put(People.NAME, "Abraham Lincoln");
values.put(People.STARRED, 1);
Uri uri = getContentResolver().insert(People.CONTENT_URI, values);
20. • Content providers are queried using ContentResolvers,
• ContentResolvers are used to query the data:
public final Cursor query (Uri uri, String[] projection, String
selection, String[ ] selectionArgs, String sortOrder)
• A managed Cursor handles all of the niceties, such as unloading
itself when the activity pauses, and requerying itself when the
activity restarts by calling Activity.startManagingCursor() method.
• A query returns a set of zero or more database records. The
retrieved data is exposed by Cursor object.
• To restrict a query to just one record, _ID value can be appended
for that record to the URI
Querying Content Provider
21. • To Update record, call ContentResolver.update()
method with the columns and values to change.
Syntax: public final int update (Uri uri, ContentValues
values, String where, String[] selectionArgs)
• The update() method returns the number of rows
updated.
Updating Content Provider
22. • To delete a single record, call ContentResolver.delete() with
the URI of a specific row.
• To delete multiple rows, call ContentResolver.delete() with
the URI of the type of record to delete (for example,
android.provider.Contacts.People.CONTENT_URI) and an
SQL WHERE clause defining which rows to delete.
Syntax : public final int delete (Uri url, String where,
String[] selectionArgs)
• The delete() method returns the number of rows deleted.
Deleting Content Provider