Tuesday 4 June 2013

Know Your Content Provider In Android

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:
  • 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
Data access methods (such as insert(Uri, ContentValues) and update(Uri, ContentValues, String, String[])) may be called from many threads at once, and must be thread-safe. Other methods (such as onCreate()) are only called from the application main thread, and must avoid performing lengthy operations
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.
Some Use case of content Provider, Below image shows a typical case scenario of content provider use:-
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:
  1.  Scheme: The scheme for content provider has a constant value: “content”.
  2.  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.
  3.  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.
  4.  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:
  1.  URI: It works exactly as explained above.
  2. 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.
  3. 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).
  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.
  5. 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
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”
// 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”
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
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 !!!!

28 comments:

  1. nice blog on Content Provider. keep it up
    THANKS

    ReplyDelete
  2. Thanks For Comment.
    I will put my best effort to write more good articles on Android

    ReplyDelete
  3. gr8 blog..but I need ur advice..

    ReplyDelete
  4. life cycle of Content Providers ?

    ReplyDelete
  5. Thanks a lot! You made a new blog entry to answer my question; I really appreciate your time and effort.
    Android Training in chennai with placement | Android Training in velachery

    ReplyDelete
  6. 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
    Click here:
    angularjs4 Training in Chennai
    Click here:
    angularjs5 Training in Chennai
    Click here:
    Selenium Training in Chennai
    Click here:
    Aws Training in Chennai

    ReplyDelete
  7. 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.
    Click here:
    Microsoft azure training in sollinganallur
    Click here:
    Microsoft azure training in btm

    ReplyDelete
  8. 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
    Blueprism training in annanagar

    Blueprism training in velachery

    Blueprism training in marathahalli


    AWS Training in chennai

    AWS Training in bangalore

    ReplyDelete
  9. It is amazing and wonderful to visit your site.Thanks for sharing this information,this is useful to me...

    java training in jayanagar | java training in electronic city

    java training in chennai | java training in USA

    ReplyDelete
  10. 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.
    Android 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

    ReplyDelete
  11. 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

    ReplyDelete
  12. Nice tips. Very innovative... Your post shows all your effort and great experience towards your work Your Information is Great if mastered very well.

    informatica mdm online training

    apache spark online training

    apache spark online training

    devops online training

    aws online training

    ReplyDelete
  13. 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
    Microsoft Azure online training
    Selenium online training
    Java online training
    Python online training
    uipath online training

    ReplyDelete
  14. Step by step procedure. Very informative. This could not be written better. Thanks for sharing.

    Regards,

    Android training in Kalyan nagar
    Python training in kalyan nagar

    ReplyDelete
  15. This comment has been removed by the author.

    ReplyDelete
  16. Your Fxtm Review Account Allows You To Login To Your Account In More Than 1 Country.

    ReplyDelete
  17. Hide 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

    ReplyDelete
  18. Native 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

Build a Custom Kernel Module for Android

Hi Guys!!!Hope you are doing well !!!. Today I will describe how you can write a custom kernel module(Hello world) for Android and load it a...