Read Contact Database with ContentResolver


SUBMITTED BY: antfuentes87

DATE: Nov. 25, 2015, 12:37 a.m.

FORMAT: Text only

SIZE: 3.2 kB

HITS: 742

  1. public class MainActivity extends AppCompatActivity {
  2. Button button;
  3. TextView textView;
  4. String TAG = MainActivity.class.getName();//LOG TAG
  5. ArrayList<String> contactName = new ArrayList<String>();
  6. ArrayList<String> contactID=new ArrayList<String>();
  7. @Override
  8. protected void onCreate(Bundle savedInstanceState) {
  9. super.onCreate(savedInstanceState);
  10. setContentView(R.layout.activity_main);
  11. button = (Button) findViewById(R.id.button);
  12. textView = (TextView) findViewById(R.id.textView);
  13. button.setOnClickListener(new OnClickListener() {
  14. @Override
  15. public void onClick(View v) {
  16. final Cursor kontakteList =
  17. getContentResolver().query(//ContentResolver
  18. ContactsContract.Contacts.CONTENT_URI,//URI
  19. new String[]{//Select
  20. ContactsContract.PhoneLookup._ID,
  21. ContactsContract.PhoneLookup.DISPLAY_NAME},
  22. null,//WHERE
  23. null,//WHERE ARGS
  24. null//ORDER
  25. );//query
  26. if(kontakteList.moveToFirst()) {//if Cursor not null
  27. String[] columnNames = kontakteList.getColumnNames();//getColumnNames
  28. Log.d(TAG, "column Names size: "+columnNames.length);
  29. StringBuilder stringBuilder=new StringBuilder();
  30. for (int i=0;i<columnNames.length;i++) {//Print Column Names
  31. Log.d(TAG, columnNames[i].toString() + " i= " + i);
  32. stringBuilder.append(columnNames[i].toString() + " ");
  33. Log.d(TAG, stringBuilder.toString() + " sb i= " + i);
  34. }//columnNames
  35. stringBuilder.append(System.getProperty("line.separator"));
  36. kontakteList.moveToFirst();
  37. while(kontakteList.isAfterLast()==false) {//for each row, until after last row is reached
  38. for (int i = 0; i < columnNames.length; i++) {//for each column
  39. Log.d(TAG, " i: " + i + " " +kontakteList.getString(kontakteList.getColumnIndex(columnNames[i])));
  40. stringBuilder.append(kontakteList.getString(kontakteList.getColumnIndex(columnNames[i])));
  41. }//for
  42. contactID.add(kontakteList.getString(kontakteList.getColumnIndex(columnNames[0])));
  43. contactName.add(kontakteList.getString(kontakteList.getColumnIndex(columnNames[1])));
  44. stringBuilder.append(System.getProperty("line.separator"));//generate a new line
  45. kontakteList.moveToNext();//move to next row
  46. }//while
  47. Log.d(TAG, stringBuilder.toString());
  48. textView.setText(stringBuilder.toString());//Display Data to Text View
  49. }//if
  50. }//onClick Method
  51. });//setOnClickListener
  52. }//onCreate
  53. }//MainActivity

comments powered by Disqus