Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android get all contacts telephone number in ArrayList

I am trying to save all contacts telephone numbers in an ArrayList but I cant find a way how. Is there a way to get them instead of picking them one by one with ContactsContract?

like image 287
Karl-John Chow Avatar asked Mar 06 '13 09:03

Karl-John Chow


2 Answers

ContentResolver cr = mContext.getContentResolver(); //Activity/Application android.content.Context     Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);     if(cursor.moveToFirst())     {         ArrayList<String> alContacts = new ArrayList<String>();         do         {             String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));              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())                  {                     String contactNumber = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));                     alContacts.add(contactNumber);                     break;                 }                 pCur.close();             }          } while (cursor.moveToNext()) ;     } 
like image 194
Santhosh Avatar answered Sep 29 '22 06:09

Santhosh


Try this:

Cursor managedCursor = getContentResolver()     .query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,      new String[] {Phone._ID, Phone.DISPLAY_NAME, Phone.NUMBER}, null, null,  Phone.DISPLAY_NAME + " ASC"); 

And by traversing through the cursor, you can store all this data in any data structure of your choice.

like image 39
mudit Avatar answered Sep 29 '22 07:09

mudit