Atkobeau
Atkobeau

Reputation: 109

Android Contacts Can't retrieve data

Android Contacts is driving me mad! This code is returning empty cursors, but the contacts exists! Can anyone see what I can't?

        ContentResolver cr = getContentResolver();
        String query = ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = " +pickedID;
        Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,query , null, null);
        pCur.moveToFirst();
            while (pCur.moveToNext()) {
                    contactPhone.setText(pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DATA)));
                } 
                pCur.close();

               query = ContactsContract.CommonDataKinds.Email.CONTACT_ID +" = " +pickedID;
                pCur = cr.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null,query , null, null);
                pCur.moveToFirst();
                        while (pCur.moveToNext()) {
                            contactPhone.setText(pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA)));
                        } 
                        pCur.close();

Upvotes: 0

Views: 872

Answers (3)

Greven
Greven

Reputation: 21

I had the same problem with the null cursor and my problem was that, I had forgotten to add the following line of code in the Manifest.xml file:

uses-permission android:name="android.permission.READ_CONTACTS"

Upvotes: 2

badtea
badtea

Reputation: 11

I'm not sure if this is the entire cause of the problem, but you are calling

pCur.moveToFirst();

which moves the cursor to the first entry. Then you immediately call

while (pCur.moveToNext())

which moves the cursor to the second entry. So you are skipping the first entry.

Leave out the pCur.moveToFirst(); and just leave the while loop and see if that helps.

Upvotes: 1

Twobard
Twobard

Reputation: 2583

I think the root of your problem is how you initially retrieve the contact list.

 Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,query , null, null);

should be..

Cursor pCur = cr.query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null);

Upvotes: 0

Related Questions