Content providers are one of the primary building blocks of Android applications, providing content to applications. They encapsulate data and provide it to applications through the single ContentResolver interface. A content provider is only required if you need to share data between multiple applications.
Content providers manage access to a structured set of data. They encapsulate the data, and provide mechanisms for defining data security.
Content providers are the standard interface that connects data in one process with code running in another process.
When you want to access data in a content provider, you use the ContentResolver object in your application's Context to communicate with the provider as a client. The ContentResolver object communicates with the provider object, an instance of a class that implements ContentProvider. The provider object receives data requests from clients, performs the requested action, and returns the results.
You don't need to develop your own provider if you don't intend to share your data with other applications. However, you do need your own provider to provide custom search suggestions in your own application. You also need your own provider if you want to copy and paste complex data or files from your application to other applications. For example, the contacts data is used by multiple applications and must be stored in a content provider. If you don't need to share data amongst multiple applications you can use a database directly via SQLiteDatabase.
When a request is made via a ContentResolver the system inspects the authority of the given URI and passes the request to the content provider registered with the authority. The content provider can interpret the rest of the URI however it wants. The UriMatcher class is helpful for parsing URIs.
The primary methods that need to be implemented are:
getType(Uri) which returns the MIME type of data in the content provider.
Now I am going to show some more explnation view of content provider. Below image shows the basic operation and relation of content provider in Android App:-
Examples of built-in Content Providers in Android OS are:
Content Provider Life Cycle:-
DELETION
Deletion uses the same arguments as update; with the exception of ContentValues argument, which is not required as there will not be any substituted values.
CODE EXAMPLE FOR Deletion:
In case of Insert operation, the URI must be directory based. In all the other cases, the URIs can be either ID based or directory based.
I will discuss some more on Content Provider in my next Blog !!!
Thanks
Happy Coding !!!!
Content providers manage access to a structured set of data. They encapsulate the data, and provide mechanisms for defining data security.
Content providers are the standard interface that connects data in one process with code running in another process.
When you want to access data in a content provider, you use the ContentResolver object in your application's Context to communicate with the provider as a client. The ContentResolver object communicates with the provider object, an instance of a class that implements ContentProvider. The provider object receives data requests from clients, performs the requested action, and returns the results.
You don't need to develop your own provider if you don't intend to share your data with other applications. However, you do need your own provider to provide custom search suggestions in your own application. You also need your own provider if you want to copy and paste complex data or files from your application to other applications. For example, the contacts data is used by multiple applications and must be stored in a content provider. If you don't need to share data amongst multiple applications you can use a database directly via SQLiteDatabase.
When a request is made via a ContentResolver the system inspects the authority of the given URI and passes the request to the content provider registered with the authority. The content provider can interpret the rest of the URI however it wants. The UriMatcher class is helpful for parsing URIs.
The primary methods that need to be implemented are:
- onCreate() which is called to initialize the provider
- query(Uri, String[], String, String[], String) which returns data to the caller
- insert(Uri, ContentValues) which inserts new data into the content provider
- update(Uri, ContentValues, String, String[]) which updates existing data in the content provider
- delete(Uri, String, String[]) which deletes data from the content provider
getType(Uri) which returns the MIME type of data in the content provider.
Now I am going to show some more explnation view of content provider. Below image shows the basic operation and relation of content provider in Android App:-
Examples of built-in Content Providers in Android OS are:
- Contacts
- MediaStore
- Bookmarks
- Settings and more.
Content Provider Life Cycle:-
- Content provider is initiated first time it is used via a call to onCreate().
- There is no callback for cleaning up after the provider.
- When modifying the data (insert/update/delete), open/close database atomically.
- When reading the data, leave database open or else the data will get garbage collected.
Here are some step to access Content Provider:-
Step 1: Accessing a Content Provider
Content URI is one of the arguments used to identify the data in a provider. It has four parts:
- Scheme: The scheme for content provider has a constant value: “content”.
- Authority: It is the symbolic name of the provider, and is unique for each one. This is how we single out the desired content provider from a list of so many.
- Path: Path helps distinguish the required data from the complete database. For instance, the Call Log Content Provider differentiates between Missed Calls, Received calls etc. using different paths.
- ID: It is not a mandatory component, and may not be present in the URI; but if present, it should be numeric. For instance, if you want to access a specific music file from your Media Content Provider, you would specify an ID as well.
The process
Using the provider authority, the ContentResolver identifies the correct content provider (as authority is unique for each content provider). Having done that, the path component of URI is used to select the correct (requested) data table. In case an ID is present, the provider would know what exact data is being requested. URI’s are of two types: (1)ID Based : If id is specified (2)Directory Based: if id is not specified
Step 2: How to retrieve data from a Content Provider
Even though the ContentResolver has access to the data table now, it cannot retrieve the required data unless the application has “read access permission” for that particular provider. This permission is defined in the manifest file of each content provider.
All that an application (that wants to access this database) has to do is to request this permission.
QUERYING
Now, we have accessed the provider, and have permission to retrieve data from it. The next step is to construct the query to request the required action from the provider.
Here are the arguments used while querying:
- URI: It works exactly as explained above.
- Projection: The query should return a set of columns from the entire database table. This is known as projection. Passing null will return all columns, which is inefficient.
- Selection Clause: A filter declaring which rows to return, formatted as an SQL WHERE clause (excluding the WHERE itself). Passing null will return all rows for the given URI. For instance, if you enter an alphabet (say ‘P’) in the search column of your address book, then it would return all the contact details starting with ‘P’. However, if you do not enter anything in the search bar, the complete list of contacts is retrieved (the selection clause is set to ‘null’ in such cases).
- Selection Argument: You may include “?s” in selection, which will be replaced by the values from selectionArgs, in the order that they appear in the selection.
- SortOrder: SQL ORDER BY clause (excluding the ORDER BY itself). Passing null will fetch the results which may be unordered.
CODE EXAMPLE for Querying:
Searching for Phone numbers in Contacts
Searching for Phone numbers in Contacts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
| Cursor cursor = contentresolver.query(ContactsContract.Contacts.CONTENT_URI, null , null , null , null ); int count = cursor.getCount(); if (count > 0 ) { String contactDetails = "" ; while (cursor.moveToNext()) { String columnId = ContactsContract.Contacts._ID; int cursorIndex = cursor.getColumnIndex(columnId); String id = cursor.getString(cursorIndex); String name = cursor.getString(cursor .getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)); int numCount = Integer.parseInt(cursor.getString(cursor .getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))); if (numCount > 0 ) { Cursor phoneCursor = contentresolver.query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null , CommonDataKinds.Phone.CONTACT_ID+ " = ?" , new String[] { id }, null ); while (phoneCursor.moveToNext()) { String phoneNo = phoneCursor.getString(phoneCursor .getColumnIndex(ContactsContract.CommonDataKinds. Phone.NUMBER)); contactDetails += "Name: " + name + ", Phone No: " + phoneNo + "\n" ; } phoneCursor.close(); } } } |
INSERTION
Let us suppose you want to insert new contacts to your address book. ContentValues object is used to do these insertions. The ContentValue object keys and the Content Provider columns must match to achieve this. Here’s an example for this:
CODE EXAMPLE FOR Insertion :
The operation is to insert new entry with name “Saurabh” and number “9967543212”
Let us suppose you want to insert new contacts to your address book. ContentValues object is used to do these insertions. The ContentValue object keys and the Content Provider columns must match to achieve this. Here’s an example for this:
CODE EXAMPLE FOR Insertion :
The operation is to insert new entry with name “Saurabh” and number “9967543212”
// Operation
ArrayList ops =
new
ArrayList();
int
rawContactInsertIndex = ops.size();
ops.add(ContentProviderOperation.newInsert(RawContacts.CONTENT_URI)
.withValue(RawContacts.ACCOUNT_TYPE,
null
)
.withValue(RawContacts.ACCOUNT_NAME,
null
).build());
ops.add(ContentProviderOperation
.newInsert(Data.CONTENT_URI)
.withValueBackReference(Data.RAW_CONTACT_ID,rawContactInsertIndex)
.withValue(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE)
.withValue(StructuredName.DISPLAY_NAME, “Saurabh”).build());
ops.add(ContentProviderOperation.newInsert(Data.CONTENT_URI)
.withValueBackReference(Data.RAW_CONTACT_ID,rawContactInsertIndex)
.withValue(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE)
.withValue(Phone.NUMBER, “
9986785423
”)
.withValue(Phone.TYPE, Phone.TYPE_MOBILE).build());
getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
UPDATING
To update a content provider the following arguments are used:
1) URI: The URI of the Content Provider
2) ContentValues: This contains the values that would replace the existing data.
3) Selection Clause: This can help select the specific records to update
4) Selection Argument: You may include “?s” in selection, which will be replaced by the values from selectionArgs, in the order that they appear in the selection.
Once again, the keys of the ContentValues object must match the columns in the Content Provider; otherwise, the update would not occur.
CODE EXAMPLE FOR Updation:
Updating the phone number where name is “Saurabh”
To update a content provider the following arguments are used:
1) URI: The URI of the Content Provider
2) ContentValues: This contains the values that would replace the existing data.
3) Selection Clause: This can help select the specific records to update
4) Selection Argument: You may include “?s” in selection, which will be replaced by the values from selectionArgs, in the order that they appear in the selection.
Once again, the keys of the ContentValues object must match the columns in the Content Provider; otherwise, the update would not occur.
CODE EXAMPLE FOR Updation:
Updating the phone number where name is “Saurabh”
1
2
3
4
5
6
7
8
| String where = ContactsContract.Data.DISPLAY_NAME + " = ? " ; String[] params = new String[] { “Saurabht” }; ArrayList ops = new ArrayList(); ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI) .withSelection(where, params) .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, “ 9876543216 ”) .build()); getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops); |
Deletion uses the same arguments as update; with the exception of ContentValues argument, which is not required as there will not be any substituted values.
CODE EXAMPLE FOR Deletion:
1
2
3
4
5
6
| String where = ContactsContract.Data.DISPLAY_NAME + " = ? " ; String[] params = new String[] { “Rajnikant” }; ArrayList ops = new ArrayList(); ops.add(ContentProviderOperation.newDelete(ContactsContract.RawContacts.CONTENT_URI) .withSelection(where, params).build()); getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops); |
In case of Insert operation, the URI must be directory based. In all the other cases, the URIs can be either ID based or directory based.
I will discuss some more on Content Provider in my next Blog !!!
Thanks
Happy Coding !!!!
nice blog on Content Provider. keep it up
ReplyDeleteTHANKS
Thanks For Comment.
ReplyDeleteI will put my best effort to write more good articles on Android
gr8 blog..but I need ur advice..
ReplyDeletelife cycle of Content Providers ?
ReplyDeleteThanks a lot! You made a new blog entry to answer my question; I really appreciate your time and effort.
ReplyDeleteAndroid Training in chennai with placement | Android Training in velachery
It's interesting that many of the bloggers to helped clarify a few things for me as well as giving.Most of ideas can be nice content.The people to give them a good shake to get your point and across the command
ReplyDeleteClick here:
angularjs4 Training in Chennai
Click here:
angularjs5 Training in Chennai
Click here:
Selenium Training in Chennai
Click here:
Aws Training in Chennai
A universal message I suppose, not giving up is the formula for success I think. Some things take longer than others to accomplish, so people must understand that they should have their eyes on the goal, and that should keep them motivated to see it out til the end.
ReplyDeleteClick here:
Microsoft azure training in sollinganallur
Click here:
Microsoft azure training in btm
Useful information.I am actual blessed to read this article.thanks for giving us this advantageous information.I acknowledge this post.and I would like bookmark this post.Thanks
ReplyDeleteBlueprism training in annanagar
Blueprism training in velachery
Blueprism training in marathahalli
AWS Training in chennai
AWS Training in bangalore
It is amazing and wonderful to visit your site.Thanks for sharing this information,this is useful to me...
ReplyDeletejava training in jayanagar | java training in electronic city
java training in chennai | java training in USA
Well Said, you have furnished the right information that will be useful to anyone at all time. Thanks for sharing your Ideas.
ReplyDeleteData Science training in rajaji nagar | Data Science with Python training in chenni
Data Science training in electronic city | Data Science training in USA
Data science training in pune | Data science training in kalyan nagar
Thank you for sharing such great information with us. I really appreciate everything that you’ve done here and am glad to know that you really care about the world that we live in.
ReplyDeleteAndroid Training in Chennai
Android Training Institute in Chennai
Android Classes in Chennai
Android Training Chennai
Android Courses in Chennai
Android Mobile apps Development Training in Chennai
I have visited this blog first time and i got a lot of informative data from here which is quiet helpful for me indeed.
ReplyDeleteangularjs-Training in velachery
angularjs Training in bangalore
angularjs Training in bangalore
angularjs Training in btm
angularjs Training in electronic-city
Hi,
ReplyDeleteI must appreciate you for providing such a valuable content for us. This is one amazing piece of article. Helped a lot in increasing my knowledge.
Salesforce Admin Training in Chennai
Salesforce Developer 501 Training in Chennai
Salesforce Developer 502 Training in Chennai
Cloud computing Training institutes in Chennai
Best Cloud computing Training in Chennai
Cloud computing institutes in Chennai
Great information on your site here. I love this post because we can get some useful information from your blog. I expect more post from you guys. php Website development in USA
ReplyDeleteThe admin of this blog has really shared a needed information in a simple way. Kindly continue sharing this king of useful information.
ReplyDeleteIELTS Classes in Mumbai
IELTS Coaching in Mumbai
Best IELTS Coaching in Mumbai
IELTS Center in Mumbai
IELTS Training in Mumbai
Best IELTS Classes in Mumbai
IELTS Class in Mumbai
Nice tips. Very innovative... Your post shows all your effort and great experience towards your work Your Information is Great if mastered very well.
ReplyDeleteinformatica mdm online training
apache spark online training
apache spark online training
devops online training
aws online training
Excellent blog, I wish to share your post with my folks circle. It’s really helped me a lot, so keep sharing post like this
ReplyDeleteMicrosoft Azure online training
Selenium online training
Java online training
Python online training
uipath online training
Step by step procedure. Very informative. This could not be written better. Thanks for sharing.
ReplyDeleteRegards,
Android training in Kalyan nagar
Python training in kalyan nagar
Very nice posts. this could not be explained better. Thanks for sharing, Keep up the good work.
ReplyDeletePython training in Bellandur
Java Training in Bellandur
BluePrism training in Bellandurr
Selenium Training in Bellandur
Very nice posts. this could not be explained better. Thanks for sharing, Keep up the good work.
ReplyDeletedevops training in Bellandur
SalesForce developer Training in Bellandur
AWS training in Bellandur
Data Analytics Training in Bellandur
this was helful article ...great content ....thanx
ReplyDeleteThis comment has been removed by the author.
ReplyDeleteIt's helpful for me my friend. Also great blog here with all of the valuable information you have.
ReplyDeleteAWS training in chennai | AWS training in annanagar | AWS training in omr | AWS training in porur | AWS training in tambaram | AWS training in velachery
Useful blog.Thank you for such a great effort. Java training in Chennai | Certification | Online Training Course | Java training in Bangalore | Certification | Online Training Course | Java training in Hyderabad | Certification | Online Training Course | Java Training in Coimbatore | Certification | Online Training Course | Java Training in Online | Certification | Online Training Course
ReplyDeleteYour Fxtm Review Account Allows You To Login To Your Account In More Than 1 Country.
ReplyDeleteHide All IP Crack is the best software that bypasses your original IP address and hides it over the internet so that no one gets your info.Hide All Ip Trial Reset
ReplyDeleteNative Instruments Massive 5.4.6 Crack seems to be sound-generating software. The above program could be used as a VA component inside a Computer.Massive Vst Free Download Full Version
ReplyDelete