SlideShare a Scribd company logo
1 of 20
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.
Understand SQLite Database with Android's SQLiteOpenHelper and Content Providers
Understand SQLite Database with Android's SQLiteOpenHelper and Content Providers
Understand SQLite Database with Android's SQLiteOpenHelper and Content Providers

More Related Content

Similar to Understand SQLite Database with Android's SQLiteOpenHelper and Content Providers

springdatajpa-up.pdf
springdatajpa-up.pdfspringdatajpa-up.pdf
springdatajpa-up.pdfssuser0562f1
 
Sqlite
SqliteSqlite
SqliteKumar
 
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, environmentjoearunraja2
 
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 & DatabasesMuhammad Sajid
 
Introduction to ADO.NET
Introduction to ADO.NETIntroduction to ADO.NET
Introduction to ADO.NETrchakra
 
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 trenchesIsmail Mayat
 
Asp .Net Database Connectivity Presentation.pptx
Asp .Net Database Connectivity Presentation.pptxAsp .Net Database Connectivity Presentation.pptx
Asp .Net Database Connectivity Presentation.pptxsridharu1981
 
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 CategoriesMuhammad Sajid
 
VISUAL BASIC .net data accesss vii
VISUAL BASIC .net data accesss viiVISUAL BASIC .net data accesss vii
VISUAL BASIC .net data accesss viiargusacademy
 
WEB-MODULE 4.pdf
WEB-MODULE 4.pdfWEB-MODULE 4.pdf
WEB-MODULE 4.pdfDeepika A B
 

Similar to Understand SQLite Database with Android's SQLiteOpenHelper and Content Providers (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
 
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
 
WEB-MODULE 4.pdf
WEB-MODULE 4.pdfWEB-MODULE 4.pdf
WEB-MODULE 4.pdf
 

Recently uploaded

Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 

Recently uploaded (20)

Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 

Understand SQLite Database with Android's SQLiteOpenHelper and Content Providers

  • 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.