WHAT ARE CONTENT PROVIDERS
Content Providers are used by an app to:
1. access data stored by itself
2. access data stored by other apps
3. provide a way to share data with other apps.
Every android app runs inside its own process. Content Providers are the standard interface that connects data in one process with code running in another process.
Use content providers if you plan to share data.
In this example, we would get all the contacts list from the Contacts app of our phone and display the names of the contact in a listview.
Create a new Android Project and go to the Android Manifest.xml. For accessing other app’s data in android we need to give permission to our app. This is done by adding permission in AndroidMainfest.xml file. For reading contacts we would give the following android permission. Just add this line in your androidmanifest.xml
Inside MainActivity, we need to declare a listview which would list all the contacts name. For that, add a listview inside your MainActivity’s layout file as shown below.
After adding the listview, initialize it inside the onCreate() method of MainActivity.
Now, we should set the adapter on the listview. For creating a default arrayadapter use:
where ad is the arraylist of type String. Declare an arraylist:
Set the adapter we created above on the listview.
For retrieving all the contacts, we need to run a query using getContentResolver() method of Context class. Return the results of the query to a Cursor object. Cursors are used to provide read-write access to the results returned by a query.
Cursor contacts= getContentResolver().query(uri, projection, selection, selectionArgs, sortOrder);
uri= The content URI
projection = The columns to return for each row
selection = Selection criteria
selectionArgs = Selection criteria
sortOrder = The sort order for the returned rows
So, using the above method, our uri will become = ContactsContract.Contacts.CONTENT_URI and everything can be null. ContactsContract.Contacts is a table which shows rows representing different people, based on aggregations of raw contact rows.
Cursor contacts= getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null,null,null);
Now that we have all the contacts in our cursor object. We need to iterate over the data and add each contact to the arraylist. Cursor provides a method cursor.moveToNext() which can be used to iterate over the entire cursor object.
Here’s how to use the method:
//To get Column Index of Contact Name
int nameIndex= contacts.getColumnIndex(PhoneLookup.DISPLAY_NAME);
//Getting the Contact Name from the Column Index
String contactName= contacts.getString(nameIndex);
//Adding the contactname to Array List
FULL MAINACTIVITY CODE
RUN YOUR APP
Run the app and see all your contacts in a listview.