SlideShare a Scribd company logo
Mobile Application with Database
Dr.P.Karthikeyan
Associate Professor
Department of Information Technology
Thiagarajar College of Engineering
Madurai 625 015
• 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
• 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
• 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
• 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
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
• 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
• 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);
• 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
• 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
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
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
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);
• 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
• 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
• 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
Activity
Application
Activity
Application
Activity
Content Provider
Service
Application
Data
SQLite
XML
Remote
Store
Content Resolver Content Resolver
Content Resolver
Content Provider
• 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
• 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);
• 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
• 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
• 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
Android Database

More Related Content

PPT
Collection Framework in java
PDF
5 collection framework
PPT
Java collections concept
PPTX
Collections framework in java
PDF
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
PPSX
Collections - Lists, Sets
Collection Framework in java
5 collection framework
Java collections concept
Collections framework in java
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Collections - Lists, Sets

What's hot (19)

PPTX
collection framework in java
PPTX
Java util
PPTX
Java 103 intro to java data structures
DOCX
Java collections notes
PDF
Java Collection framework
PPSX
Collections - Maps
PPT
Collections in Java
PPT
java collections
PDF
Collections in Java Notes
PPT
Java collection
PPTX
บทที่4
PPT
Synapseindia dot net development chapter 8 asp dot net
PDF
Lecture 4 - Object Interaction and Collections
PPSX
Collections - Array List
PDF
Collections Api - Java
PPTX
Java - Collections framework
PDF
Java Collections Tutorials
PDF
Collections In Java
PPTX
Java Collections Framework Inroduction with Video Tutorial
collection framework in java
Java util
Java 103 intro to java data structures
Java collections notes
Java Collection framework
Collections - Maps
Collections in Java
java collections
Collections in Java Notes
Java collection
บทที่4
Synapseindia dot net development chapter 8 asp dot net
Lecture 4 - Object Interaction and Collections
Collections - Array List
Collections Api - Java
Java - Collections framework
Java Collections Tutorials
Collections In Java
Java Collections Framework Inroduction with Video Tutorial
Ad

Similar to Android Database (20)

PPTX
SQLite Opening .pptx
PPTX
Android webinar class_6
PPTX
Shshsjsjsjs-4 - Copdjsjjsjsjsjakakakaaky.pptx
PDF
Android contentprovider
PPTX
Contains the SQLite database management classes that an application would use...
PPT
Sqlite
PPTX
Spring data jpa
PDF
springdatajpa-up.pdf
PDF
Cursor & Content Value.pdf
PPTX
Quick dive to pandas
PDF
Full Text Search with Lucene
PPT
02._Object-Oriented_Programming_Concepts.ppt
PDF
ElasticSearch: Distributed Multitenant NoSQL Datastore and Search Engine
PPTX
Introduction to Azure Data Lake and U-SQL for SQL users (SQL Saturday 635)
PDF
Advanced database lab oracle structure query language
PPT
Advanced c#
PPT
Persistences
PDF
Solr Recipes Workshop
KEY
Modules Building Presentation
PDF
Sql Server2008
SQLite Opening .pptx
Android webinar class_6
Shshsjsjsjs-4 - Copdjsjjsjsjsjakakakaaky.pptx
Android contentprovider
Contains the SQLite database management classes that an application would use...
Sqlite
Spring data jpa
springdatajpa-up.pdf
Cursor & Content Value.pdf
Quick dive to pandas
Full Text Search with Lucene
02._Object-Oriented_Programming_Concepts.ppt
ElasticSearch: Distributed Multitenant NoSQL Datastore and Search Engine
Introduction to Azure Data Lake and U-SQL for SQL users (SQL Saturday 635)
Advanced database lab oracle structure query language
Advanced c#
Persistences
Solr Recipes Workshop
Modules Building Presentation
Sql Server2008
Ad

More from Dr Karthikeyan Periasamy (9)

PDF
Web tools - angular js
PDF
PDF
System thinking about system
PPTX
Android - Activity, Services
PPTX
Android Introduction
PPTX
Arduino Programming
PPTX
Internet of Things
PDF
Padlet Creation
PDF
Canvas LMS Creation
Web tools - angular js
System thinking about system
Android - Activity, Services
Android Introduction
Arduino Programming
Internet of Things
Padlet Creation
Canvas LMS Creation

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