Hello Friends !!! In this tutorial we are going to retrieve the contacts from the android mobile using ContentProvider.
- Here is an example of ContentProvider ,so to implement it just follow the steps given below .
- Create a new project for example name it “ContactsDemo”.
- Now in your activity_main.xml file in the graphical layout take three buttons and name it as CONNECT , PREV , NEXT .
- Also take a Large text where we would display the text or the contact.
- Hence the layout will look like as shown below:
- Now on the buttons (i.e button property)in the activity_main.xml file set the android:onClick=”prevClicked” for previous button,do the same for the Next and the Connect button.
- Now in the MainActivity.java file extend the class with Activity.
- Declare the ArrayList , index and TextView as private.
- Therefore the code for declaring it private is given :
- private ArrayList names=new ArrayList();
- private static int index = 0;
- Private static TextView tvName = null;
- Now in onCreate ( ) method add the following line of code which will find the id of the textView.
- tvName = (TextView)find ViewById(R.id.name);
- name is the id of the TextView which is generated not to be typed manually.
- Now write the code for the connect button.
- The CONTENT_URI gives the authority to access or to map the contact .
- So now your window will look as shown below :
- Similarly write code for next and the previous buttons as given below.
- The most important thing is the android manifest :
- If you are going to look at contacts or any other information or any other system provider you need to provide a permission.
- In this case we are providing a permission as shown below in AndroidManifest.xml file:
- Now Run your MainActivity .java file and you will see the following screen :
- Now click on the connect button it will display the first name from the contact database :
- Thus we have successfully implemented ContentProvider.
[code language=”java”]public void connectClicked(View v)
Uri allContacts = ContactsContract.Contacts.CONTENT_URI;
Cursor cur = this.getContentResolver().query(
allContacts, //the uri
null, //rows to get back,null for all
null, //where clause
null, //where clause arguments
null //order by clause
/* for each column in the cursor , fetch the name of the contact into the ArrayList names :*/
int nameCol = cur.getColumnIndex(PhoneLookup.DISPLAY_NAME);
String contact = cur.getString(nameCol);
//display the first name
//always close the cursor when done
[code language=”java”]public void nextClicked(View v)
//if we are not at the end of the list :
//display the next name :
public void prevClicked(View v)
//If we are not at the beginning of the list :
if(index > 0)
//display the previous name :
<uses-permission android:name=” android.permission.READ_CONTACTS”/>