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 !!!!
0 komentar:
Posting Komentar