Advertisement
hacknik

Android fetch Contact

Apr 9th, 2015
208
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.36 KB | None | 0 0
  1. Android fetch Contact
  2. public void fetchContacts() {
  3.  
  4. String phoneNumber = null;
  5. String email = null;
  6.  
  7. Uri CONTENT_URI = ContactsContract.Contacts.CONTENT_URI;
  8. String _ID = ContactsContract.Contacts._ID;
  9. String DISPLAY_NAME = ContactsContract.Contacts.DISPLAY_NAME;
  10. String HAS_PHONE_NUMBER = ContactsContract.Contacts.HAS_PHONE_NUMBER;
  11.  
  12. Uri PhoneCONTENT_URI = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
  13. String Phone_CONTACT_ID = ContactsContract.CommonDataKinds.Phone.CONTACT_ID;
  14. String NUMBER = ContactsContract.CommonDataKinds.Phone.NUMBER;
  15.  
  16. Uri EmailCONTENT_URI = ContactsContract.CommonDataKinds.Email.CONTENT_URI;
  17. String EmailCONTACT_ID = ContactsContract.CommonDataKinds.Email.CONTACT_ID;
  18. String DATA = ContactsContract.CommonDataKinds.Email.DATA;
  19.  
  20. StringBuffer output = new StringBuffer();
  21.  
  22. ContentResolver contentResolver = getContentResolver();
  23.  
  24. Cursor cursor = contentResolver.query(CONTENT_URI, null, null, null,
  25. null);
  26.  
  27. // Loop for every contact in the phone
  28. if (cursor.getCount() > 0) {
  29.  
  30. while (cursor.moveToNext()) {
  31.  
  32. String contact_id = cursor
  33. .getString(cursor.getColumnIndex(_ID));
  34. String name = cursor.getString(cursor
  35. .getColumnIndex(DISPLAY_NAME));
  36.  
  37. int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor
  38. .getColumnIndex(HAS_PHONE_NUMBER)));
  39.  
  40. if (hasPhoneNumber > 0) {
  41.  
  42. output.append("\n First Name:" + name);
  43.  
  44. // Query and loop for every phone number of the contact
  45. Cursor phoneCursor = contentResolver.query(
  46. PhoneCONTENT_URI, null, Phone_CONTACT_ID + " = ?",
  47. new String[] { contact_id }, null);
  48.  
  49. while (phoneCursor.moveToNext()) {
  50. phoneNumber = phoneCursor.getString(phoneCursor
  51. .getColumnIndex(NUMBER));
  52. output.append("\n Phone number:" + phoneNumber);
  53.  
  54. }
  55.  
  56. phoneCursor.close();
  57.  
  58. // Query and loop for every email of the contact
  59. Cursor emailCursor = contentResolver.query(
  60. EmailCONTENT_URI, null, EmailCONTACT_ID + " = ?",
  61. new String[] { contact_id }, null);
  62.  
  63. while (emailCursor.moveToNext()) {
  64.  
  65. email = emailCursor.getString(emailCursor
  66. .getColumnIndex(DATA));
  67.  
  68. output.append("\n Email:" + email);
  69.  
  70. }
  71.  
  72. emailCursor.close();
  73. }
  74.  
  75. output.append("\n");
  76. }
  77.  
  78. outputText.setText(output);
  79. }
  80. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement