I am getting all the phonebook contact details as an array. For that I wrote the following code:
package com.android.toggle2;
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import android.app.ListActivity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.View;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
public class Toggle3 extends ListActivity
{
ArrayList<NameValuePair> list = new ArrayList<NameValuePair>();
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Cursor mCursor = getContacts();
startManagingCursor(mCursor);
// Now create a new list adapter bound to the cursor.
// SimpleListAdapter is designed for binding to a Cursor.
ListAdapter adapter = new SimpleCursorAdapter(this, // Context.
android.R.layout.simple_list_item_multiple_choice, // Specify the row template
// to use (here, two
// columns bound to the
// two retrieved cursor
// rows).
mCursor, // Pass in the cursor to bind to.
// Array of cursor columns to bind to.
new String[] { ContactsContract.Contacts.DISPLAY_NAME ,
ContactsContract.Contacts._ID},
// Parallel array of which template objects to bind to those
// columns.
new int[] { android.R.id.text1, android.R.id.text2 });
// Bind to our new adapter.
setListAdapter(adapter);
final ListView listView = getListView();
listView.setItemsCanFocus(false);
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
}
private Cursor getContacts()
{
// Run query
Uri uri = ContactsContract.Contacts.CONTENT_URI;
String[] projection = new String[] { ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME };
String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP + " = '"
+ ("1") + "'";
String[] selectionArgs = null;
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME+ " COLLATE LOCALIZED ASC";
return managedQuery(uri, projection, selection, selectionArgs,sortOrder);
}
protected void onListItemClick(ListView l, View v, int position, long id)
{
super.onListItemClick(l, v, position, id);
//here i want to handle the event.and should display the details of that contacts in another screen .
//Toast.makeText(Toggle3.this,"Item in position " + position + " clicked",Toast.LENGTH_LONG).show();
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null);
if (cur.getCount() > 0)
{
while (cur.moveToNext())
{
String ids = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
list.add(new BasicNameValuePair("name",name.toString()));
//String number = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.NUMBER));
if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0)
{
//Query phone here.
Cursor pCur = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",
new String[]{ids}, null);
while(pCur.moveToNext())
{
String number = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
list.add(new BasicNameValuePair("num",number.toString()));
}
pCur.close();
}//if
}//while
Log.i("array items", "" +list);
}//if
}//on click
}//class
While executing this application it's showing all my phonebook contacts in the application with checkboxes in each row. If I click on any name (list item) it stores all the contact details into an array. But I want to store only selected contacts. What should I change in my code.. please do needful help
I have modified your code. Now its working as per expectation. Vote my answer if it is helpful for you so that It will increase your ratings also
use the following code to retrieve contact from mobile.
I have tested. its working fine
public static void getContactNumbers(Context context) {
String contactNumber = null;
int contactNumberType = Phone.TYPE_MOBILE;
String nameOfContact = null;
if (ApplicationConstants.phoneContacts.size() <= 0) {
ContentResolver cr = context.getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
null, null, null);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
String id = cur.getString(cur
.getColumnIndex(BaseColumns._ID));
nameOfContact = cur
.getString(cur
.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (Integer
.parseInt(cur.getString(cur
.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Cursor phones = cr
.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ " = ?", new String[] { id },
null);
while (phones.moveToNext()) {
contactNumber = phones.getString(phones
.getColumnIndex(Phone.NUMBER));
contactNumberType = phones.getInt(phones
.getColumnIndex(Phone.TYPE));
Log.i(TAG, "...Contact Name ...." + nameOfContact
+ "...contact Number..." + contactNumber);
}
phones.close();
}
}
}// end of contact name cursor
cur.close();
}
}
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
while (phones.moveToNext())
{
String Name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)
String Number=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
public void readContacts()
{
int i=0;
Cursor cursor=getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,null,null,null);
count=cursor.getCount();
names=new String[count];
phno=new String[count];
while(cursor.moveToNext())
{
names[i]=cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)) ;
phno[i]=cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
i++;
}
Related
i am trying to write a program that would display the id, name and phone number of a contact in android. So far the Id and Names of the contact are displayed but the number of the contact doesn't. Can someone help me, below is the code for my program:
package com.example.oghenekaroedoh.provider;
import android.app.ListActivity;
import android.content.CursorLoader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.widget.CursorAdapter;
import android.widget.SimpleCursorAdapter;
public class Provider2Activity extends ListActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_provider);
Uri allContacts = ContactsContract.Contacts.CONTENT_URI;
//query string for our contacts
//Uri allContacts = Uri.parse("content://contacts/people");
//declare our cursor
Cursor c;
String[] projection = new String[]
{ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts.HAS_PHONE_NUMBER};
//---detect the android version
//---Projection, Filtering, and sorting
/* >>The second parameter of the managedQuery() method (third parameter for the CursorLoader class)
controls how many columns are returned by the query; this parameter is known as the projection
>>The third parameter of the managedQuery() method (fourth parameter for the CursorLoader class)
enable you to specify a SQL WHERE clause to filter the result of the query
>>The fourth parameter of the managedQuery() method (the fifth parameter for the CursorLoader class)
enables you to specify a SQL ORDER BY clause to sort the result of the query, either in ascending or descending order
* */
if (android.os.Build.VERSION.SDK_INT <11) {
//---if the device ids running on OS before Honeycomb
//use the managedQuery() of the Activity class to retrieve a managed cursor
c = managedQuery(allContacts, projection, null, null, null);
}
else {
//---Honeycomb and later use the cursor loader class to retrieve managed cursor---
CursorLoader cursorLoader = new CursorLoader(
this,
allContacts,
projection,
null,
null ,
null);
c = cursorLoader.loadInBackground();
}
//create columns for the contacts display name and the column
String[] columns = new String[] {
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts._ID};
int[] views = new int[] {R.id.contactName, R.id.contactID};
SimpleCursorAdapter adapter;
//detect the android version again..s
if (android.os.Build.VERSION.SDK_INT <11) {
//---if it is before Honeycomb---
//use the SimpleCursorAdapter class to map the cursor to a view (like textViews imageViews e.t.c)
adapter = new SimpleCursorAdapter(
this, R.layout.activity_provider, c, columns, views);
}
else {
//---Honeycomb and later---
////use the SimpleCursorAdapter class to map the cursor to a view (like textViews imageViews e.t.c)
//with an extra parameter known as CursorAdapter.FLAG_REGISTER_CURRENT_OBSERVER
adapter = new SimpleCursorAdapter(
this, R.layout.activity_provider, c, columns, views,
CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
}
this.setListAdapter(adapter);
PrintContacts(c);
}
private void PrintContacts(Cursor c)
{
//---display the contact id and name and phone number----
if (c.moveToFirst()) {
do{
//---get the contact id and name
String contactID = c.getString(c.getColumnIndex(
ContactsContract.Contacts._ID));
String contactDisplayName =
c.getString(c.getColumnIndex(
ContactsContract.Contacts.DISPLAY_NAME));
Log.v("Content Providers", contactID + ", " +
contactDisplayName);
//---get phone number---
int hasPhone =
c.getInt(c.getColumnIndex(
ContactsContract.Contacts.HAS_PHONE_NUMBER));
if (hasPhone == 1) {
Cursor phoneCursor =
getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " +
contactID, null, null);
while (phoneCursor.moveToNext()) {
Log.v("Content Providers",
phoneCursor.getString(
phoneCursor.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.NUMBER)));
}
phoneCursor.close();
}
} while (c.moveToNext());
}
}
}
I got your example working by adding a CustomAdapter MyClassAdapter which extends ArrayAdapter, and populating an ArrayList of Contact objects.
import android.app.ListActivity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.CursorLoader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.ArrayList;
public class Provider2Activity extends ListActivity {
ArrayList<Contact> contacts;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_provider2);
contacts = new ArrayList<Contact>();
Uri allContacts = ContactsContract.Contacts.CONTENT_URI;
//declare our cursor
Cursor c;
String[] projection = new String[]
{ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts.HAS_PHONE_NUMBER};
/* >>The second parameter of the managedQuery() method (third parameter for the CursorLoader class)
controls how many columns are returned by the query; this parameter is known as the projection
>>The third parameter of the managedQuery() method (fourth parameter for the CursorLoader class)
enable you to specify a SQL WHERE clause to filter the result of the query
>>The fourth parameter of the managedQuery() method (the fifth parameter for the CursorLoader class)
enables you to specify a SQL ORDER BY clause to sort the result of the query, either in ascending or descending order
* */
if (android.os.Build.VERSION.SDK_INT <11) {
//---if the device ids running on OS before Honeycomb
//use the managedQuery() of the Activity class to retrieve a managed cursor
c = managedQuery(allContacts, projection, null, null, null);
}
else {
//---Honeycomb and later use the cursor loader class to retrieve managed cursor---
CursorLoader cursorLoader = new CursorLoader(
this,
allContacts,
projection,
null,
null ,
null);
c = cursorLoader.loadInBackground();
}
PrintContacts(c);
MyClassAdapter adapter;
//detect the android version again..
if (android.os.Build.VERSION.SDK_INT <11) {
//---if it is before Honeycomb---
adapter = new MyClassAdapter(
this, R.layout.row_line, contacts);
}
else {
//---Honeycomb and later---
adapter = new MyClassAdapter(
this, R.layout.row_line, contacts);
}
this.setListAdapter(adapter);
}
private void PrintContacts(Cursor c)
{
ContentResolver cr = getContentResolver();
//---display the contact id and name and phone number----
if (c.moveToFirst()) {
do{
//---get the contact id and name
String contactID = c.getString(c.getColumnIndex(
ContactsContract.Contacts._ID));
String contactDisplayName =
c.getString(c.getColumnIndex(
ContactsContract.Contacts.DISPLAY_NAME));
Log.v("Content Providers", contactID + ", " +
contactDisplayName);
String contactDisplayPhone = "";
//---get phone number---
int hasPhone =
c.getInt(c.getColumnIndex(
ContactsContract.Contacts.HAS_PHONE_NUMBER));
if (hasPhone == 1) {
Cursor phoneCursor =
getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " +
contactID, null, null);
while (phoneCursor.moveToNext()) {
Log.v("Content Providers",
contactDisplayPhone = phoneCursor.getString(
phoneCursor.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.NUMBER)));
}
phoneCursor.close();
}
contacts.add(new Contact(contactDisplayName, contactID, contactDisplayPhone));
} while (c.moveToNext());
}
}
public class Contact{
public String contactName = "";
public String contactID = "";
public String contactNumber = "";
public Contact(String name, String id, String number){
contactName = name;
contactID = id;
contactNumber = number;
}
}
public class MyClassAdapter extends ArrayAdapter<Contact> {
private class ViewHolder {
private TextView name;
private TextView id;
private TextView number;
}
public MyClassAdapter(Context context, int textViewResourceId, ArrayList<Contact> items) {
super(context, textViewResourceId, items);
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if (convertView == null) {
convertView = LayoutInflater.from(this.getContext())
.inflate(R.layout.row_line, parent, false);
viewHolder = new ViewHolder();
viewHolder.name = (TextView) convertView.findViewById(R.id.contactName);
viewHolder.id = (TextView) convertView.findViewById(R.id.contactID);
viewHolder.number = (TextView) convertView.findViewById(R.id.contactNumber);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
Contact item = getItem(position);
if (item!= null) {
viewHolder.name.setText(item.contactName);
viewHolder.id.setText(item.contactID);
viewHolder.number.setText(item.contactNumber);
}
return convertView;
}
}
}
row_line.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView android:id="#+id/contactName"
android:textSize="16sp"
android:textStyle="bold"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<TextView android:id="#+id/contactID"
android:textSize="16sp"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<TextView android:id="#+id/contactNumber"
android:textSize="16sp"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
activity_provider2.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".Provider2Activity">
<ListView
android:id="#android:id/list"
android:layout_height="wrap_content"
android:layout_width="match_parent">
</ListView>
</RelativeLayout>
I knew their are many reference for contacts list but what I need was to get the contacts in popup menu.
When user click on button popup should show the contacts list he should be able to select the multiple friends name and contact number store them.
I had gone with the below code and get only by information I kept the popup and tried I need exactly as our mobile contacts list view.
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.widget.TextView;
public class MainActivity extends Activity {
public TextView outputText;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
outputText = (TextView) findViewById(R.id.textView1);
fetchContacts();
}
public void fetchContacts() {
String phoneNumber = null;
String email = null;
Uri CONTENT_URI = ContactsContract.Contacts.CONTENT_URI;
String _ID = ContactsContract.Contacts._ID;
String DISPLAY_NAME = ContactsContract.Contacts.DISPLAY_NAME;
String HAS_PHONE_NUMBER = ContactsContract.Contacts.HAS_PHONE_NUMBER;
Uri PhoneCONTENT_URI = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String Phone_CONTACT_ID = ContactsContract.CommonDataKinds.Phone.CONTACT_ID;
String NUMBER = ContactsContract.CommonDataKinds.Phone.NUMBER;
Uri EmailCONTENT_URI = ContactsContract.CommonDataKinds.Email.CONTENT_URI;
String EmailCONTACT_ID = ContactsContract.CommonDataKinds.Email.CONTACT_ID;
String DATA = ContactsContract.CommonDataKinds.Email.DATA;
StringBuffer output = new StringBuffer();
ContentResolver contentResolver = getContentResolver();
Cursor cursor = contentResolver.query(CONTENT_URI, null,null, null, null);
// Loop for every contact in the phone
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
String contact_id = cursor.getString(cursor.getColumnIndex( _ID );
String name = cursor.getString(cursor.getColumnIndex( DISPLAY_NAME );
int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex( HAS_PHONE_NUMBER ));
if (hasPhoneNumber > 0) {
output.append("\n First Name:" + name);
// Query and loop for every phone number of the contact
Cursor phoneCursor = contentResolver.query(PhoneCONTENT_URI, null, Phone_CONTACT_ID + " = ?", new String[] { contact_id }, null);
while (phoneCursor.moveToNext()) {
phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(NUMBER));
output.append("\n Phone number:" + phoneNumber);
}
phoneCursor.close();
// Query and loop for every email of the contact
Cursor emailCursor = contentResolver.query(EmailCONTENT_URI, null, EmailCONTACT_ID+ " = ?", new String[] { contact_id }, null);
while (emailCursor.moveToNext()) {
email = emailCursor.getString(emailCursor.getColumnIndex(DATA));
output.append("\nEmail:" + email);
}
emailCursor.close();
}
output.append("\n";
}
outputText.setText(output);
}
}
}
If some have any idea about this please help me friends.
First of all create a button and on that button click
final Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.email_dialog);//
ListView lv;
lv= (ListView ) dialog.findViewById(R.id.list);//this is your list xml
Use a multiple choice listview adapter and populate the contacts in the list view using the above code
I am using the Android Eclair 2.1 platform.
The working behind this code is, it will access all the contacts from the Emulator and will display in the list view for each contact like this
Contact Name, Contact Number, Email
There are 2 issues for this code is
I did run the program, after that I created a new contact it won't be in alphabetical order
[ eg : when I create a name starting from B it wouldn't go after A, instead it go to the last place ]
2.If a contact has no Email or Number it will receive the previous contact's Email or Number
Here is the code
public class GetAllDatas extends Activity {
ListView lvItem;
private Button btnAdd;
String displayName="", emailAddress="", phoneNumber="";
ArrayList<String> contactlist=new ArrayList<String>();
ArrayAdapter<String> itemAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lvItem = (ListView)this.findViewById(R.id.lvitems);
btnAdd = (Button)this.findViewById(R.id.btnAddItem);
itemAdapter = new ArrayAdapter<String> (this,android.R.layout.simple_list_item_1,contactlist);
lvItem.setAdapter(itemAdapter);
btnAdd.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
readContacts();
}
});
}
private void readContacts()
{
ContentResolver cr =getContentResolver();
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
while (cursor.moveToNext())
{
displayName =Cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME) );
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
Cursor emails = cr.query(Email.CONTENT_URI,null,Email.CONTACT_ID + " = " + id, null, null);
while (emails.moveToNext())
{
emailAddress = emails.getString(emails.getColumnIndex(Email.DATA));
break;
}
emails.close();
if(Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PH ONE_NUMBER))) > 0)
{
Cursor pCur =cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,ContactsContract.CommonDat aKinds.Phone.CONTACT_ID +" = ?",new String[]{id}, null);
while (pCur.moveToNext())
{
phoneNumber =pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
break;
}
pCur.close();
}
// To display the Details
contactlist.add(displayName+", "+phoneNumber+", "+ emailAddress+"\n");
itemAdapter.notifyDataSetChanged();
}
cursor.close();
}
}
Any link or site to refer and study to solve this problems if so send me the link ?
Check the tested code below
package stack.examples;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Email;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
public class GetAllDatas extends Activity {
ListView lvItem;
private Button btnAdd;
String displayName="", emailAddress="", phoneNumber="";
ArrayList<String> contactlist=new ArrayList<String>();
ArrayAdapter<String> itemAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lvItem = (ListView)this.findViewById(R.id.listView_items);
btnAdd = (Button)this.findViewById(R.id.btnAddItem);
itemAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,contactlist);
lvItem.setAdapter(itemAdapter);
btnAdd.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
readContacts();
}
});
}
private void readContacts()
{
ContentResolver cr =getContentResolver();
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
while (cursor.moveToNext())
{
displayName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
Cursor emails = cr.query(Email.CONTENT_URI,null,Email.CONTACT_ID + " = " + id, null, null);
while (emails.moveToNext())
{
emailAddress = emails.getString(emails.getColumnIndex(Email.DATA));
break;
}
emails.close();
if(Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0)
{
Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",new String[]{id}, null);
while (pCur.moveToNext())
{
phoneNumber = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
break;
}
pCur.close();
}
contactlist.add(displayName+","+phoneNumber+","+ emailAddress);
}
cursor.close();
sortList(contactlist);
itemAdapter.notifyDataSetChanged();
}
private static void sortList(List<String> aItems){
Collections.sort(aItems, String.CASE_INSENSITIVE_ORDER);
}
}
To sort the ArrayList in Alphabetical order, you can use
Collections.sort(aItems, String.CASE_INSENSITIVE_ORDER);
Happy Coding !!!
When you query the database you are missing the orderBy:
public Cursor query (String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy)
replace the last null with the column to sort by:
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
The last parameter of the query method expects the sorting order.
Please check the documentation query (Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder).
sortOrder How to order the rows, formatted as an SQL ORDER BY clause (excluding the ORDER BY itself). Passing null will use the default sort order, which may be unordered.
I am trying to retrieve name and type of the contacts stored in phone, but getting this exception. I was getting the names before but getting exception
android.database.CursorIndexOutOfBoundsException: Index -1 requested with a size of 10
when tried to retrieve name and type together. Please help. Thanks in advance.
package application.test;
import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.Contacts;
import android.util.Log;
public class TestActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String[] projection = new String[] {ContactsContract.Contacts.DISPLAY_NAME};
String[] projection1=new String[]{Phone.TYPE};
String[] projection2=new String[]{ContactsContract.Contacts._ID};
ContentResolver cr = getContentResolver();
ContentResolver ncr=getContentResolver();
ContentResolver icr=getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, projection,null, null, Contacts.DISPLAY_NAME + " ASC");
Cursor ncur=ncr.query(ContactsContract.Data.CONTENT_URI, projection1, null, null,null);
Cursor icur = icr.query(ContactsContract.RawContacts.CONTENT_URI, projection2,null, null, Contacts._ID + " ASC");
if (cur.getCount() >0 && ncur.getCount()>0 && icur.getCount()>0)
{
while (cur.moveToNext()&& ncur.moveToNext()&& icur.getCount()>0)
{
String id = icur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
String type=ncur.getString(ncur.getColumnIndex(Phone.TYPE));
if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0)
{
Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",new String[]{id}, null);
Cursor typecur = ncr.query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{id}, null)
while (pCur.moveToNext()&& typecur.moveToNext())
{
Log.d("names",name);
Log.d("types",type);
pCur.close();
}
}
}
}
}
}
When u create a cursor before reading it. Move the cursor position to first.
while (cur.moveToNext()&& ncur.moveToNext()&& icur.getCount()>0)
/* move icur to first position then read */
icur.moveFirst()
It must work
You should not create three differents cursors and contextresolver, use the same, but make the conditions in the loop in order to get what you want, I'll give you a method I wrote myself.
This will give you all the contacts in your phone which has a phone number, you'll get the idea of to implements yours:
public ArrayList<Contact> getSMSContacts(Context context){
ArrayList<Contact> contacts = new ArrayList<Contact>();
ContentResolver cr = context.getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, ContactsContract.Contacts.DISPLAY_NAME + " asc");
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Contact c = new Contact();
c.setId(Integer.parseInt(id));
c.setName(name);
Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",
new String[]{id}, null);
while (pCur.moveToNext()) {
String number = pCur.getString(
pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
c.setNumber(number);
}
pCur.close();
contacts.add(c);
}
}
}
cur.close();
return contacts;
}
After days of search I have finally got the answers..type and name get stored in data table under DATA2 column thus I queried data.content_uri and got the index of DATA2 column and its just working fine...I am getting both name and type.
I'm using this code to retrieve all contact names and phone numbers:
String[] projection = new String[]
{
People.NAME,
People.NUMBER
};
Cursor c = ctx.getContentResolver().query(People.CONTENT_URI, projection, null, null, People.NAME + " ASC");
c.moveToFirst();
int nameCol = c.getColumnIndex(People.NAME);
int numCol = c.getColumnIndex(People.NUMBER);
int nContacts = c.getCount();
do
{
// Do something
} while(c.moveToNext());
However, this will only return the primary number for each contact, but I want to get the secondary numbers as well. How can i do this?
Following code shows an easy way to read all phone numbers and names:
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
while (phones.moveToNext())
{
String name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
phones.close();
NOTE: getContentResolver is a method from the Activity context.
You can read all of the telephone numbers associated with a contact in the following manner:
Uri personUri = ContentUris.withAppendedId(People.CONTENT_URI, personId);
Uri phonesUri = Uri.withAppendedPath(personUri, People.Phones.CONTENT_DIRECTORY);
String[] proj = new String[] {Phones._ID, Phones.TYPE, Phones.NUMBER, Phones.LABEL}
Cursor cursor = contentResolver.query(phonesUri, proj, null, null, null);
Please note that this example (like yours) uses the deprecated contacts API. From eclair onwards this has been replaced with the ContactsContract API.
This code shows how to get all phone numbers for each contact.
ContentResolver cr = getActivity().getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
String id = cur.getString(cur.getColumnIndex(
ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex(
ContactsContract.Contacts.DISPLAY_NAME));
if (Integer.parseInt(cur.getString(cur.getColumnIndex(
ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Cursor pCur = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",
new String[]{id}, null);
while (pCur.moveToNext()) {
int phoneType = pCur.getInt(pCur.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.TYPE));
String phoneNumber = pCur.getString(pCur.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.NUMBER));
switch (phoneType) {
case Phone.TYPE_MOBILE:
Log.e(name + "(mobile number)", phoneNumber);
break;
case Phone.TYPE_HOME:
Log.e(name + "(home number)", phoneNumber);
break;
case Phone.TYPE_WORK:
Log.e(name + "(work number)", phoneNumber);
break;
case Phone.TYPE_OTHER:
Log.e(name + "(other number)", phoneNumber);
break;
default:
break;
}
}
pCur.close();
}
}
}
In case it helps, I've got an example that uses the ContactsContract API to first find a contact by name, then it iterates through the details looking for specific number types:
How to use ContactsContract to retrieve phone numbers and email addresses
You can get all phone contacts using this:
Cursor c = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
new String[] { ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.RawContacts.ACCOUNT_TYPE },
ContactsContract.RawContacts.ACCOUNT_TYPE + " <> 'google' ",
null, null);
check complete example HERE...........
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0)
{
System.out.println("name : " + name + ", ID : " + id);
// get the <span id="IL_AD4" class="IL_AD">phone
// number</span>
Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[] { id }, null);
while (pCur.moveToNext())
{
String phone = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
System.out.println("phone" + phone);
}
pCur.close();
Accepted answer working but not given unique numbers.
See this code, it return unique numbers.
public static void readContacts(Context context) {
if (context == null)
return;
ContentResolver contentResolver = context.getContentResolver();
if (contentResolver == null)
return;
String[] fieldListProjection = {
ContactsContract.CommonDataKinds.Phone.CONTACT_ID,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.NORMALIZED_NUMBER,
ContactsContract.Contacts.HAS_PHONE_NUMBER
};
Cursor phones = contentResolver
.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI
, fieldListProjection, null, null, null);
HashSet<String> normalizedNumbersAlreadyFound = new HashSet<>();
if (phones != null && phones.getCount() > 0) {
while (phones.moveToNext()) {
String normalizedNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NORMALIZED_NUMBER));
if (Integer.parseInt(phones.getString(phones.getColumnIndex(
ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
if (normalizedNumbersAlreadyFound.add(normalizedNumber)) {
String id = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
Log.d("test", " Print all values");
}
}
}
phones.close();
}
}
In the same way just get their other numbers using the other "People" references
People.TYPE_HOME
People.TYPE_MOBILE
People.TYPE_OTHER
People.TYPE_WORK
This one finally gave me the answer I was looking for. It lets you retrieve all the names and phone numbers of the contacts on the phone.
package com.test;
import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
public class TestContacts extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
if (cur != null && cur.getCount() > 0) {
while (cur.moveToNext()) {
if (Integer.parseInt.equals(cur.getString(cur.getColumnIndex(
ContactsContract.Contacts.HAS_PHONE_NUMBER)))) {
String id = cur.getString(cur.getColumnIndex(
ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex(
ContactsContract.Contacts.DISPLAY_NAME));
Cursor pCur = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ " = ?", new String[] { id }, null);
int i = 0;
int pCount = pCur.getCount();
String[] phoneNum = new String[pCount];
String[] phoneType = new String[pCount];
while (pCur != null && pCur.moveToNext()) {
phoneNum[i] = pCur.getString(pCur.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.NUMBER));
phoneType[i] = pCur.getString(pCur.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.TYPE));
i++;
}
}
}
}
}
}
I fixed my need belove
manifest permissions
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS"/>
<!-- Read Contacts from phone -->
<uses-permission android:name="android.permission.read_contacts" />
<uses-permission android:name="android.permission.read_phone_state" />
<uses-permission android:name="android.permission.READ_CALL_LOG" />
Note: After giving permissions at manifest some mobile phones can deny if so you need to go Settings--> Applications--> find your application click on it and
turn On the permissions needed
btn_readallcontacks.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
List<User> userList = new ArrayList<User>();
while (phones.moveToNext()) {
User user = new User();
user.setNamee(phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)));
user.setPhone(phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
userList.add(user);
Log.d(TAG, "Name : " + user.getNamee().toString());
Log.d(TAG, "Phone : " + user.getPhone().toString());
}
phones.close();
}
});
You can get all the contact all those which have no number and all those which have no name from this piece of code
public void readContacts() {
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, ContactsContract.RawContacts.DISPLAY_NAME_PRIMARY + " ASC");
ContactCount = cur.getCount();
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
String phone = null;
if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
System.out.println("name : " + name + ", ID : " + id);
// get the phone number
Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[]{id}, null);
while (pCur.moveToNext()) {
phone = pCur.getString(
pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
System.out.println("phone" + phone);
}
pCur.close();
}
if (phone == "" || name == "" || name.equals(phone)) {
if (phone.equals(""))
getAllContact.add(new MissingPhoneModelClass("No Number", name, id));
if (name.equals("") || name.equals(phone))
getAllContact.add(new MissingPhoneModelClass(phone, "No Name", id));
} else {
if(TextUtils.equals(phone,null)){
getAllContact.add(new MissingPhoneModelClass("No Number", name, id));
}
else {
getAllContact.add(new MissingPhoneModelClass(phone, name, id));
}
}
}
}
}
One thing can be done you have to give the permission in the manifest for contact READ and WRITE
After that you can create the model class for the list which can be use to add all the contact here is the model class
public class PhoneModelClass {
private String number;
private String name;
private String id;
private String rawId;
public PhoneModelClass(String number, String name, String id, String rawId) {
this.number = number;
this.name = name;
this.id = id;
this.rawId = rawId;
}
public PhoneModelClass(String number, String name, String id) {
this.number = number;
this.name = name;
this.id = id;
}
public String getRawId() {
return rawId;
}
public void setRawId(String rawId) {
this.rawId = rawId;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
Enjoy :)
Load contacts in background using CursorLoader:
CursorLoader cursor = new CursorLoader(this, ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
Cursor managedCursor = cursor.loadInBackground();
int number = managedCursor.getColumnIndex(ContactsContract.Contacts.Data.DATA1);
int name = managedCursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
int index = 0;
while (managedCursor.moveToNext()) {
String phNumber = managedCursor.getString(number);
String phName = managedCursor.getString(name);
}
Here's how to use ContentsContract API to fetch your contacts in your Phone Book.
You'll need to add these permissions in your AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
Then, you can run this method to loop through all your contacts.
Here's an example to query fields like Name and Phone Number, you can configure yourself to use CommonDataKinds, it query other fields in your Contact.
https://developer.android.com/reference/android/provider/ContactsContract.CommonDataKinds
private fun readContactsOnDevice() {
val context = requireContext()
if (ContextCompat.checkSelfPermission(
context, Manifest.permission.WRITE_CONTACTS
) != PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(
context, Manifest.permission.READ_CONTACTS
) != PackageManager.PERMISSION_GRANTED
) {
requestPermissions(
arrayOf(Manifest.permission.READ_CONTACTS, Manifest.permission.WRITE_CONTACTS), 1
)
return
}
val contentResolver = context.contentResolver
val contacts = contentResolver.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null, null, null, null
)
while (contacts?.moveToNext() == true) {
val name = contacts.getString(
contacts.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)
)
val phoneNumber = contacts.getString(
contacts.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)
)
Timber.i("Name: $name, Phone Number: $phoneNumber")
}
}
package com.example.readcontacts;
import java.util.ArrayList;
import android.app.Activity; import android.app.ProgressDialog;
import android.content.ContentResolver; import
android.database.Cursor; import android.net.Uri; import
android.os.Bundle; import android.os.Handler; import
android.provider.ContactsContract; import android.view.View; import
android.widget.AdapterView; import
android.widget.AdapterView.OnItemClickListener; import
android.widget.ArrayAdapter; import android.widget.ListView; import
android.widget.Toast;
public class MainActivity extends Activity { private ListView
mListView; private ProgressDialog pDialog; private Handler
updateBarHandler;
ArrayList<String> contactList; Cursor cursor; int counter;
#Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pDialog = new ProgressDialog(this); pDialog.setMessage("Reading
contacts..."); pDialog.setCancelable(false); pDialog.show();
mListView = (ListView) findViewById(R.id.list); updateBarHandler
=new Handler();
// Since reading contacts takes more time, let's run it on a separate thread. new Thread(new Runnable() {
#Override public void run() {
getContacts(); } }).start();
// Set onclicklistener to the list item.
mListView.setOnItemClickListener(new OnItemClickListener() {
#Override public void onItemClick(AdapterView<?> parent, View
view,
int position, long id) {
//TODO Do whatever you want with the list data
Toast.makeText(getApplicationContext(), "item clicked : \n"+contactList.get(position), Toast.LENGTH_SHORT).show(); }
}); }
public void getContacts() {
contactList = new ArrayList<String>();
String phoneNumber = null; String email = null;
Uri CONTENT_URI = ContactsContract.Contacts.CONTENT_URI; String
_ID = ContactsContract.Contacts._ID; String DISPLAY_NAME = ContactsContract.Contacts.DISPLAY_NAME; String HAS_PHONE_NUMBER =
ContactsContract.Contacts.HAS_PHONE_NUMBER;
Uri PhoneCONTENT_URI =
ContactsContract.CommonDataKinds.Phone.CONTENT_URI; String
Phone_CONTACT_ID =
ContactsContract.CommonDataKinds.Phone.CONTACT_ID; String NUMBER =
ContactsContract.CommonDataKinds.Phone.NUMBER;
Uri EmailCONTENT_URI =
ContactsContract.CommonDataKinds.Email.CONTENT_URI; String
EmailCONTACT_ID = ContactsContract.CommonDataKinds.Email.CONTACT_ID;
String DATA = ContactsContract.CommonDataKinds.Email.DATA;
StringBuffer output;
ContentResolver contentResolver = getContentResolver();
cursor = contentResolver.query(CONTENT_URI, null,null, null,
null);
// Iterate every contact in the phone if (cursor.getCount() > 0)
{
counter = 0; while (cursor.moveToNext()) {
output = new StringBuffer();
// Update the progress message
updateBarHandler.post(new Runnable() {
public void run() {
pDialog.setMessage("Reading contacts : "+ counter++ +"/"+cursor.getCount());
}
});
String contact_id = cursor.getString(cursor.getColumnIndex( _ID ));
String name = cursor.getString(cursor.getColumnIndex( DISPLAY_NAME ));
int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex(
HAS_PHONE_NUMBER )));
if (hasPhoneNumber > 0) {
output.append("\n First Name:" + name);
//This is to read multiple phone numbers associated with the same contact
Cursor phoneCursor = contentResolver.query(PhoneCONTENT_URI, null, Phone_CONTACT_ID + " = ?", new String[] { contact_id }, null);
while (phoneCursor.moveToNext()) {
phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(NUMBER));
output.append("\n Phone number:" + phoneNumber);
}
phoneCursor.close();
// Read every email id associated with the contact
Cursor emailCursor = contentResolver.query(EmailCONTENT_URI, null, EmailCONTACT_ID+ " =
?", new String[] { contact_id }, null);
while (emailCursor.moveToNext()) {
email = emailCursor.getString(emailCursor.getColumnIndex(DATA));
output.append("\n Email:" + email);
}
emailCursor.close();
}
// Add the contact to the ArrayList
contactList.add(output.toString()); }
// ListView has to be updated using a ui thread
runOnUiThread(new Runnable() {
#Override
public void run() {
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.list_item,
R.id.text1, contactList);
mListView.setAdapter(adapter);
} });
// Dismiss the progressbar after 500 millisecondds
updateBarHandler.postDelayed(new Runnable() {
#Override
public void run() {
pDialog.cancel();
} }, 500); }
}
}
List item
Code to get contact name (Ascending order) and number
For more reference: show contact in listview
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME+" ASC");
while (phones.moveToNext())
{
String name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
phones.close();