SlideShare a Scribd company logo
Database: Understanding of SQLite
database, connecting with the database
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.
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
Code
• DBOpenHelper hp = new DBOpenHelper(e,
DBOpenHelper.name, null, DBOpenHelper.v);
• SQLiteDatabase db;
• try
• {
• db = DBOpenHelper.getWritableDatabase();
• }
• catch (SQLiteException e)
• {
• db = DBOpenHelper.getReadableDatabase();
• }
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);
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.
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.
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”/>
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.
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
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.
• 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.
query()
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.
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;
• }
• @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);
• }
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.
SQLite Opening .pptx
SQLite Opening .pptx
SQLite Opening .pptx

More Related Content

Similar to SQLite Opening .pptx

Spring data jpa
Spring data jpaSpring data jpa
Spring data jpa
Jeevesh Pandey
 
springdatajpa-up.pdf
springdatajpa-up.pdfspringdatajpa-up.pdf
springdatajpa-up.pdf
ssuser0562f1
 
Sqlite
SqliteSqlite
Sqlite
Kumar
 
Solr Recipes Workshop
Solr Recipes WorkshopSolr Recipes Workshop
Solr Recipes WorkshopErik Hatcher
 
Full Text Search with Lucene
Full Text Search with LuceneFull Text Search with Lucene
Full Text Search with LuceneWO Community
 
J2EE : Java servlet and its types, environment
J2EE : Java servlet and its types, environmentJ2EE : Java servlet and its types, environment
J2EE : Java servlet and its types, environment
joearunraja2
 
Android App Development 05 : Saving Data
Android App Development 05 : Saving DataAndroid App Development 05 : Saving Data
Android App Development 05 : Saving DataAnuchit Chalothorn
 
Data Transfer between Activities & Databases
Data Transfer between Activities & DatabasesData Transfer between Activities & Databases
Data Transfer between Activities & Databases
Muhammad Sajid
 
Advanced c#
Advanced c#Advanced c#
Advanced c#
AkashThakrar
 
Big query
Big queryBig query
Big query
Tanvi Parikh
 
Introduction to ADO.NET
Introduction to ADO.NETIntroduction to ADO.NET
Introduction to ADO.NET
rchakra
 
Examiness hints and tips from the trenches
Examiness hints and tips from the trenchesExaminess hints and tips from the trenches
Examiness hints and tips from the trenches
Ismail Mayat
 
Asp .Net Database Connectivity Presentation.pptx
Asp .Net Database Connectivity Presentation.pptxAsp .Net Database Connectivity Presentation.pptx
Asp .Net Database Connectivity Presentation.pptx
sridharu1981
 
Secrets of highly_avail_oltp_archs
Secrets of highly_avail_oltp_archsSecrets of highly_avail_oltp_archs
Secrets of highly_avail_oltp_archsTarik Essawi
 
Products and Categories
Products and CategoriesProducts and Categories
Products and Categories
Muhammad Sajid
 
Database Testing
Database TestingDatabase Testing
Database Testing
Siva Kotilingam Pallikonda
 
VISUAL BASIC .net data accesss vii
VISUAL BASIC .net data accesss viiVISUAL BASIC .net data accesss vii
VISUAL BASIC .net data accesss vii
argusacademy
 
Data-Analytics using python (Module 4).pptx
Data-Analytics using python (Module 4).pptxData-Analytics using python (Module 4).pptx
Data-Analytics using python (Module 4).pptx
DRSHk10
 
PHP - Introduction to PHP Date and Time Functions
PHP -  Introduction to  PHP Date and Time FunctionsPHP -  Introduction to  PHP Date and Time Functions
PHP - Introduction to PHP Date and Time Functions
Vibrant Technologies & Computers
 

Similar to SQLite Opening .pptx (20)

Spring data jpa
Spring data jpaSpring data jpa
Spring data jpa
 
springdatajpa-up.pdf
springdatajpa-up.pdfspringdatajpa-up.pdf
springdatajpa-up.pdf
 
Sqlite
SqliteSqlite
Sqlite
 
Solr Recipes Workshop
Solr Recipes WorkshopSolr Recipes Workshop
Solr Recipes Workshop
 
Full Text Search with Lucene
Full Text Search with LuceneFull Text Search with Lucene
Full Text Search with Lucene
 
J2EE : Java servlet and its types, environment
J2EE : Java servlet and its types, environmentJ2EE : Java servlet and its types, environment
J2EE : Java servlet and its types, environment
 
CodeIgniter & MVC
CodeIgniter & MVCCodeIgniter & MVC
CodeIgniter & MVC
 
Android App Development 05 : Saving Data
Android App Development 05 : Saving DataAndroid App Development 05 : Saving Data
Android App Development 05 : Saving Data
 
Data Transfer between Activities & Databases
Data Transfer between Activities & DatabasesData Transfer between Activities & Databases
Data Transfer between Activities & Databases
 
Advanced c#
Advanced c#Advanced c#
Advanced c#
 
Big query
Big queryBig query
Big query
 
Introduction to ADO.NET
Introduction to ADO.NETIntroduction to ADO.NET
Introduction to ADO.NET
 
Examiness hints and tips from the trenches
Examiness hints and tips from the trenchesExaminess hints and tips from the trenches
Examiness hints and tips from the trenches
 
Asp .Net Database Connectivity Presentation.pptx
Asp .Net Database Connectivity Presentation.pptxAsp .Net Database Connectivity Presentation.pptx
Asp .Net Database Connectivity Presentation.pptx
 
Secrets of highly_avail_oltp_archs
Secrets of highly_avail_oltp_archsSecrets of highly_avail_oltp_archs
Secrets of highly_avail_oltp_archs
 
Products and Categories
Products and CategoriesProducts and Categories
Products and Categories
 
Database Testing
Database TestingDatabase Testing
Database Testing
 
VISUAL BASIC .net data accesss vii
VISUAL BASIC .net data accesss viiVISUAL BASIC .net data accesss vii
VISUAL BASIC .net data accesss vii
 
Data-Analytics using python (Module 4).pptx
Data-Analytics using python (Module 4).pptxData-Analytics using python (Module 4).pptx
Data-Analytics using python (Module 4).pptx
 
PHP - Introduction to PHP Date and Time Functions
PHP -  Introduction to  PHP Date and Time FunctionsPHP -  Introduction to  PHP Date and Time Functions
PHP - Introduction to PHP Date and Time Functions
 

Recently uploaded

Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
SOFTTECHHUB
 
The Metaverse and AI: how can decision-makers harness the Metaverse for their...
The Metaverse and AI: how can decision-makers harness the Metaverse for their...The Metaverse and AI: how can decision-makers harness the Metaverse for their...
The Metaverse and AI: how can decision-makers harness the Metaverse for their...
Jen Stirrup
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Aggregage
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
Ralf Eggert
 
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
UiPathCommunity
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
sonjaschweigert1
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
Adtran
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
Assure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyesAssure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 

Recently uploaded (20)

Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
 
The Metaverse and AI: how can decision-makers harness the Metaverse for their...
The Metaverse and AI: how can decision-makers harness the Metaverse for their...The Metaverse and AI: how can decision-makers harness the Metaverse for their...
The Metaverse and AI: how can decision-makers harness the Metaverse for their...
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
 
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
Assure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyesAssure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyes
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 

SQLite Opening .pptx

  • 1. Database: Understanding of SQLite database, connecting with the database
  • 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.