SlideShare a Scribd company logo
1 of 23
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

What's hot

collection framework in java
collection framework in javacollection framework in java
collection framework in javaMANOJ KUMAR
 
Java 103 intro to java data structures
Java 103   intro to java data structuresJava 103   intro to java data structures
Java 103 intro to java data structuresagorolabs
 
Java Collection framework
Java Collection frameworkJava Collection framework
Java Collection frameworkankitgarg_er
 
Collections - Maps
Collections - Maps Collections - Maps
Collections - Maps Hitesh-Java
 
Collections in Java
Collections in JavaCollections in Java
Collections in JavaKhasim Cise
 
java collections
java collectionsjava collections
java collectionsjaveed_mhd
 
Synapseindia dot net development chapter 8 asp dot net
Synapseindia dot net development  chapter 8 asp dot netSynapseindia dot net development  chapter 8 asp dot net
Synapseindia dot net development chapter 8 asp dot netSynapseindiappsdevelopment
 
Lecture 4 - Object Interaction and Collections
Lecture 4 - Object Interaction and CollectionsLecture 4 - Object Interaction and Collections
Lecture 4 - Object Interaction and CollectionsSyed Afaq Shah MACS CP
 
Collections - Array List
Collections - Array List Collections - Array List
Collections - Array List Hitesh-Java
 
Collections Api - Java
Collections Api - JavaCollections Api - Java
Collections Api - JavaDrishti Bhalla
 
Java - Collections framework
Java - Collections frameworkJava - Collections framework
Java - Collections frameworkRiccardo Cardin
 
Collections In Java
Collections In JavaCollections In Java
Collections In JavaBinoj T E
 
Java Collections Framework Inroduction with Video Tutorial
Java Collections Framework Inroduction with Video TutorialJava Collections Framework Inroduction with Video Tutorial
Java Collections Framework Inroduction with Video TutorialMarcus Biel
 

What's hot (19)

collection framework in java
collection framework in javacollection framework in java
collection framework in java
 
Java util
Java utilJava util
Java util
 
Java 103 intro to java data structures
Java 103   intro to java data structuresJava 103   intro to java data structures
Java 103 intro to java data structures
 
Java collections notes
Java collections notesJava collections notes
Java collections notes
 
Java Collection framework
Java Collection frameworkJava Collection framework
Java Collection framework
 
Collections - Maps
Collections - Maps Collections - Maps
Collections - Maps
 
Collections in Java
Collections in JavaCollections in Java
Collections in Java
 
java collections
java collectionsjava collections
java collections
 
Collections in Java Notes
Collections in Java NotesCollections in Java Notes
Collections in Java Notes
 
Java collection
Java collectionJava collection
Java collection
 
บทที่4
บทที่4บทที่4
บทที่4
 
Synapseindia dot net development chapter 8 asp dot net
Synapseindia dot net development  chapter 8 asp dot netSynapseindia dot net development  chapter 8 asp dot net
Synapseindia dot net development chapter 8 asp dot net
 
Lecture 4 - Object Interaction and Collections
Lecture 4 - Object Interaction and CollectionsLecture 4 - Object Interaction and Collections
Lecture 4 - Object Interaction and Collections
 
Collections - Array List
Collections - Array List Collections - Array List
Collections - Array List
 
Collections Api - Java
Collections Api - JavaCollections Api - Java
Collections Api - Java
 
Java - Collections framework
Java - Collections frameworkJava - Collections framework
Java - Collections framework
 
Java Collections Tutorials
Java Collections TutorialsJava Collections Tutorials
Java Collections Tutorials
 
Collections In Java
Collections In JavaCollections In Java
Collections In Java
 
Java Collections Framework Inroduction with Video Tutorial
Java Collections Framework Inroduction with Video TutorialJava Collections Framework Inroduction with Video Tutorial
Java Collections Framework Inroduction with Video Tutorial
 

Similar to Android Database

SQLite Opening .pptx
SQLite Opening .pptxSQLite Opening .pptx
SQLite Opening .pptxImranS18
 
Android webinar class_6
Android webinar class_6Android webinar class_6
Android webinar class_6Edureka!
 
Shshsjsjsjs-4 - Copdjsjjsjsjsjakakakaaky.pptx
Shshsjsjsjs-4 - Copdjsjjsjsjsjakakakaaky.pptxShshsjsjsjs-4 - Copdjsjjsjsjsjakakakaaky.pptx
Shshsjsjsjs-4 - Copdjsjjsjsjsjakakakaaky.pptx086ChintanPatel1
 
Android contentprovider
Android contentproviderAndroid contentprovider
Android contentproviderKrazy Koder
 
Sqlite
SqliteSqlite
SqliteKumar
 
springdatajpa-up.pdf
springdatajpa-up.pdfspringdatajpa-up.pdf
springdatajpa-up.pdfssuser0562f1
 
Cursor & Content Value.pdf
Cursor & Content Value.pdfCursor & Content Value.pdf
Cursor & Content Value.pdfuttamrao7
 
Full Text Search with Lucene
Full Text Search with LuceneFull Text Search with Lucene
Full Text Search with LuceneWO Community
 
02._Object-Oriented_Programming_Concepts.ppt
02._Object-Oriented_Programming_Concepts.ppt02._Object-Oriented_Programming_Concepts.ppt
02._Object-Oriented_Programming_Concepts.pptYonas D. Ebren
 
ElasticSearch: Distributed Multitenant NoSQL Datastore and Search Engine
ElasticSearch: Distributed Multitenant NoSQL Datastore and Search EngineElasticSearch: Distributed Multitenant NoSQL Datastore and Search Engine
ElasticSearch: Distributed Multitenant NoSQL Datastore and Search EngineDaniel N
 
Introduction to Azure Data Lake and U-SQL for SQL users (SQL Saturday 635)
Introduction to Azure Data Lake and U-SQL for SQL users (SQL Saturday 635)Introduction to Azure Data Lake and U-SQL for SQL users (SQL Saturday 635)
Introduction to Azure Data Lake and U-SQL for SQL users (SQL Saturday 635)Michael Rys
 
Solr Recipes Workshop
Solr Recipes WorkshopSolr Recipes Workshop
Solr Recipes WorkshopErik Hatcher
 
Modules Building Presentation
Modules Building PresentationModules Building Presentation
Modules Building Presentationhtyson
 
Lucene And Solr Document Classification
Lucene And Solr Document ClassificationLucene And Solr Document Classification
Lucene And Solr Document ClassificationAlessandro Benedetti
 
Apache Solr Workshop
Apache Solr WorkshopApache Solr Workshop
Apache Solr WorkshopJSGB
 

Similar to Android Database (20)

SQLite Opening .pptx
SQLite Opening .pptxSQLite Opening .pptx
SQLite Opening .pptx
 
Android webinar class_6
Android webinar class_6Android webinar class_6
Android webinar class_6
 
Shshsjsjsjs-4 - Copdjsjjsjsjsjakakakaaky.pptx
Shshsjsjsjs-4 - Copdjsjjsjsjsjakakakaaky.pptxShshsjsjsjs-4 - Copdjsjjsjsjsjakakakaaky.pptx
Shshsjsjsjs-4 - Copdjsjjsjsjsjakakakaaky.pptx
 
Android contentprovider
Android contentproviderAndroid contentprovider
Android contentprovider
 
Sqlite
SqliteSqlite
Sqlite
 
Spring data jpa
Spring data jpaSpring data jpa
Spring data jpa
 
springdatajpa-up.pdf
springdatajpa-up.pdfspringdatajpa-up.pdf
springdatajpa-up.pdf
 
Cursor & Content Value.pdf
Cursor & Content Value.pdfCursor & Content Value.pdf
Cursor & Content Value.pdf
 
Quick dive to pandas
Quick dive to pandasQuick dive to pandas
Quick dive to pandas
 
Full Text Search with Lucene
Full Text Search with LuceneFull Text Search with Lucene
Full Text Search with Lucene
 
02._Object-Oriented_Programming_Concepts.ppt
02._Object-Oriented_Programming_Concepts.ppt02._Object-Oriented_Programming_Concepts.ppt
02._Object-Oriented_Programming_Concepts.ppt
 
ElasticSearch: Distributed Multitenant NoSQL Datastore and Search Engine
ElasticSearch: Distributed Multitenant NoSQL Datastore and Search EngineElasticSearch: Distributed Multitenant NoSQL Datastore and Search Engine
ElasticSearch: Distributed Multitenant NoSQL Datastore and Search Engine
 
Introduction to Azure Data Lake and U-SQL for SQL users (SQL Saturday 635)
Introduction to Azure Data Lake and U-SQL for SQL users (SQL Saturday 635)Introduction to Azure Data Lake and U-SQL for SQL users (SQL Saturday 635)
Introduction to Azure Data Lake and U-SQL for SQL users (SQL Saturday 635)
 
Advanced c#
Advanced c#Advanced c#
Advanced c#
 
Persistences
PersistencesPersistences
Persistences
 
Solr Recipes Workshop
Solr Recipes WorkshopSolr Recipes Workshop
Solr Recipes Workshop
 
Modules Building Presentation
Modules Building PresentationModules Building Presentation
Modules Building Presentation
 
Sql Server2008
Sql Server2008Sql Server2008
Sql Server2008
 
Lucene And Solr Document Classification
Lucene And Solr Document ClassificationLucene And Solr Document Classification
Lucene And Solr Document Classification
 
Apache Solr Workshop
Apache Solr WorkshopApache Solr Workshop
Apache Solr Workshop
 

More from Dr Karthikeyan Periasamy (9)

Web tools - angular js
Web tools - angular jsWeb tools - angular js
Web tools - angular js
 
System types
System typesSystem types
System types
 
System thinking about system
System thinking   about systemSystem thinking   about system
System thinking about system
 
Android - Activity, Services
Android - Activity, ServicesAndroid - Activity, Services
Android - Activity, Services
 
Android Introduction
Android IntroductionAndroid Introduction
Android Introduction
 
Arduino Programming
Arduino ProgrammingArduino Programming
Arduino Programming
 
Internet of Things
Internet of ThingsInternet of Things
Internet of Things
 
Padlet Creation
Padlet CreationPadlet Creation
Padlet Creation
 
Canvas LMS Creation
Canvas LMS CreationCanvas LMS Creation
Canvas LMS Creation
 

Recently uploaded

Chandigarh Call Girls Service ❤️🍑 9115573837 👄🫦Independent Escort Service Cha...
Chandigarh Call Girls Service ❤️🍑 9115573837 👄🫦Independent Escort Service Cha...Chandigarh Call Girls Service ❤️🍑 9115573837 👄🫦Independent Escort Service Cha...
Chandigarh Call Girls Service ❤️🍑 9115573837 👄🫦Independent Escort Service Cha...Niamh verma
 
Call US Pooja 9892124323 ✓Call Girls In Mira Road ( Mumbai ) secure service,
Call US Pooja 9892124323 ✓Call Girls In Mira Road ( Mumbai ) secure service,Call US Pooja 9892124323 ✓Call Girls In Mira Road ( Mumbai ) secure service,
Call US Pooja 9892124323 ✓Call Girls In Mira Road ( Mumbai ) secure service,Pooja Nehwal
 
Model Call Girl in Shalimar Bagh Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Shalimar Bagh Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Shalimar Bagh Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Shalimar Bagh Delhi reach out to us at 🔝8264348440🔝soniya singh
 
CALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best Night Fun service
CALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best Night Fun serviceCALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best Night Fun service
CALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best Night Fun serviceanilsa9823
 
哪里有卖的《俄亥俄大学学历证书+俄亥俄大学文凭证书+俄亥俄大学学位证书》Q微信741003700《俄亥俄大学学位证书复制》办理俄亥俄大学毕业证成绩单|购买...
哪里有卖的《俄亥俄大学学历证书+俄亥俄大学文凭证书+俄亥俄大学学位证书》Q微信741003700《俄亥俄大学学位证书复制》办理俄亥俄大学毕业证成绩单|购买...哪里有卖的《俄亥俄大学学历证书+俄亥俄大学文凭证书+俄亥俄大学学位证书》Q微信741003700《俄亥俄大学学位证书复制》办理俄亥俄大学毕业证成绩单|购买...
哪里有卖的《俄亥俄大学学历证书+俄亥俄大学文凭证书+俄亥俄大学学位证书》Q微信741003700《俄亥俄大学学位证书复制》办理俄亥俄大学毕业证成绩单|购买...wyqazy
 
CALL ON ➥8923113531 🔝Call Girls Saharaganj Lucknow best sexual service
CALL ON ➥8923113531 🔝Call Girls Saharaganj Lucknow best sexual serviceCALL ON ➥8923113531 🔝Call Girls Saharaganj Lucknow best sexual service
CALL ON ➥8923113531 🔝Call Girls Saharaganj Lucknow best sexual serviceanilsa9823
 
Powerful Love Spells in Arkansas, AR (310) 882-6330 Bring Back Lost Lover
Powerful Love Spells in Arkansas, AR (310) 882-6330 Bring Back Lost LoverPowerful Love Spells in Arkansas, AR (310) 882-6330 Bring Back Lost Lover
Powerful Love Spells in Arkansas, AR (310) 882-6330 Bring Back Lost LoverPsychicRuben LoveSpells
 
9892124323 | Book Call Girls in Juhu and escort services 24x7
9892124323 | Book Call Girls in Juhu and escort services 24x79892124323 | Book Call Girls in Juhu and escort services 24x7
9892124323 | Book Call Girls in Juhu and escort services 24x7Pooja Nehwal
 

Recently uploaded (8)

Chandigarh Call Girls Service ❤️🍑 9115573837 👄🫦Independent Escort Service Cha...
Chandigarh Call Girls Service ❤️🍑 9115573837 👄🫦Independent Escort Service Cha...Chandigarh Call Girls Service ❤️🍑 9115573837 👄🫦Independent Escort Service Cha...
Chandigarh Call Girls Service ❤️🍑 9115573837 👄🫦Independent Escort Service Cha...
 
Call US Pooja 9892124323 ✓Call Girls In Mira Road ( Mumbai ) secure service,
Call US Pooja 9892124323 ✓Call Girls In Mira Road ( Mumbai ) secure service,Call US Pooja 9892124323 ✓Call Girls In Mira Road ( Mumbai ) secure service,
Call US Pooja 9892124323 ✓Call Girls In Mira Road ( Mumbai ) secure service,
 
Model Call Girl in Shalimar Bagh Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Shalimar Bagh Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Shalimar Bagh Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Shalimar Bagh Delhi reach out to us at 🔝8264348440🔝
 
CALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best Night Fun service
CALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best Night Fun serviceCALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best Night Fun service
CALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best Night Fun service
 
哪里有卖的《俄亥俄大学学历证书+俄亥俄大学文凭证书+俄亥俄大学学位证书》Q微信741003700《俄亥俄大学学位证书复制》办理俄亥俄大学毕业证成绩单|购买...
哪里有卖的《俄亥俄大学学历证书+俄亥俄大学文凭证书+俄亥俄大学学位证书》Q微信741003700《俄亥俄大学学位证书复制》办理俄亥俄大学毕业证成绩单|购买...哪里有卖的《俄亥俄大学学历证书+俄亥俄大学文凭证书+俄亥俄大学学位证书》Q微信741003700《俄亥俄大学学位证书复制》办理俄亥俄大学毕业证成绩单|购买...
哪里有卖的《俄亥俄大学学历证书+俄亥俄大学文凭证书+俄亥俄大学学位证书》Q微信741003700《俄亥俄大学学位证书复制》办理俄亥俄大学毕业证成绩单|购买...
 
CALL ON ➥8923113531 🔝Call Girls Saharaganj Lucknow best sexual service
CALL ON ➥8923113531 🔝Call Girls Saharaganj Lucknow best sexual serviceCALL ON ➥8923113531 🔝Call Girls Saharaganj Lucknow best sexual service
CALL ON ➥8923113531 🔝Call Girls Saharaganj Lucknow best sexual service
 
Powerful Love Spells in Arkansas, AR (310) 882-6330 Bring Back Lost Lover
Powerful Love Spells in Arkansas, AR (310) 882-6330 Bring Back Lost LoverPowerful Love Spells in Arkansas, AR (310) 882-6330 Bring Back Lost Lover
Powerful Love Spells in Arkansas, AR (310) 882-6330 Bring Back Lost Lover
 
9892124323 | Book Call Girls in Juhu and escort services 24x7
9892124323 | Book Call Girls in Juhu and escort services 24x79892124323 | Book Call Girls in Juhu and escort services 24x7
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