Andrew
Andrew

Reputation: 8130

Storing and retrieving contacts in android

I've got a contact picker in my app which returns a contact and from that I'm storing several bits of information into sharedPreferences. In the shared preferences I'm using the lookup key to hold the data (as the android docs seem to suggest)

This part all seems fine and I get and store the lookup key.

My problem is then went I come to getting back the contacts looking up the contact via the lookup key sometimes seems to return null

The following details come from the contact picker

 Contact lookup key from the contact picker: 850i%2bw7vj56otre6eqa9b9t7wa%3d%3d  
 Contact id: 2958

Then I try to lookup the contact based upon the lookup key using the following code to get the contact id:

Uri lookupUri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI, Uri.encode("850i%2bw7vj56otre6eqa9b9t7wa%3d%3d"));
Uri res = ContactsContract.Contacts.lookupContact(context.getContentResolver(), lookupUri);

After doing this "res" is null even though I know the id is valid as it's come from the contact picker.

Putting in some logging the res uri in the lookup is:

content://com.android.contacts/contacts/lookup/850i%252bw7vj56otre6eqa9b9t7wa%253d%253d

Which (once encoded) is what I thought it should be. Can anyone spot what I'm doing wrong?

The thing is, it works for most people (myself included) but some people are coming across this.

Upvotes: 1

Views: 1457

Answers (2)

ChD Computers
ChD Computers

Reputation: 3137

As Dheeraj V.S. said, you should not neither encode or decode the lookupkey it is allready encoded so re-encoding it may have strange results. Now I think that your approach creates problems with contacts that have their id changed. If this is the case then you should try to append the contact's last known key in your lookup uri and see what happens.

Something like:

Uri lookupUri = ContentUris.withAppendedId(Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI, lookupkey), contactid);

I think that android needs the contactid in order to determine if it has changed although the documentations states that it is optional.

Hope this helps.

Upvotes: 1

Dheeraj Vepakomma
Dheeraj Vepakomma

Reputation: 28767

Use Uri.decode() instead of Uri.encode().

Edit:
According to the documentation:

Lookup key should be appended unencoded - it is stored in the encoded form, ready for use in a URI.

So you should neither encode or decode the URI. Pass it as it is.

Upvotes: 2

Related Questions