Unable to load contacts


Ask by : abidkhan303 November 04, 2012 11:58

I have Tried number of available examples which helps to load contacts from phone. It works fine on emulator but when i try on real time mobile then it crashes. Can any one send me tested piece of code which is working flawless. then i can compare with my code.

one failed code example.

Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
if (phones.getCount() > 0)
{
    while (phones.moveToNext())
    {
            name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

    }
phones.close();

Kindly help.

View original question

Answer by : Maxim ShoustinNovember 04, 2012 11:58

Be sure that phones is not null. If not null add this row to move pointer to 1st phone:

cursor.moveToFirst();

Here is snippets of code as example how it should work:

Uri contactData = data.getData();
    //Cursor cursor =  managedQuery(contactData, null, null, null, null);
    Cursor cursor =  cr.query(contactData, null, null, null, null);
    cursor.moveToFirst();
    String name = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
    String id = cursor.getString(cursor.getColumnIndexOrThrow(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 number = pCur.getString(pCur.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER));

            break; // ? we want only 1 value
        } 
        pCur.close();
    }

    cursor.close();

Suppose it will help you

View original answer