Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read all contacts from phone and sim Android

EDIT ::: The code works. It was a problem with Eclipse, and the code displays the output in logcat as intended.

Android 2.3.3

I am pretty new to using contentproviders. I just want to try out an example of how to retrieve contacts from my phone. I have seen few examples, but none worked for me, when I tried it over my SAMSUNG Mobile.

Here is the code that i have used...

public class Class_Add_Contact extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_add_contact);

        readContacts();    
    }

    private void readContacts() {
        // TODO Auto-generated method stub

        ContentResolver cr = getContentResolver();
        Cursor cur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,null, null);

        while (cur.moveToNext()) {

            String name =cur.getString(cur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));    
            String phoneNumber = cur.getString(cur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

            System.out.println(name + "   " + phoneNumber);
            }
    }
}

The code seems fine, but there aren't any numbers displayed in the logcat. What could be wrong?

like image 345
Vamsi Challa Avatar asked Apr 06 '13 15:04

Vamsi Challa


1 Answers

try this

Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null); 

while (cursor.moveToNext()) {
    String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
    String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
    System.out.println(contactId + "   " + name);
}
cursor.close();

it returns the contact's name and the id (the id is probably the row number of the contacts table)

like image 117
Elior Avatar answered Sep 19 '22 02:09

Elior