How to get last inserted RawContacts ID after newInsert into address book programactically?

StackOverflow https://stackoverflow.com/questions/7911101

سؤال

I succeeded in inserting contacts into the address book and I need to save a reference of the contact in my app. I figured that the best way to save the reference is to get the RawContacts ID itself.

Is there a way for me to directly get the ID back from the address book right after the insertion of the the new contact? Or do I have to get every records out and compare them with my data to get the RawContacts ID?

I do my insert using this code:

ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
int rawContactInsertIndex = ops.size();
ops.add(ContentProviderOperation.newInsert(RawContacts.CONTENT_URI)
    .withValue(RawContacts.ACCOUNT_TYPE, null)
    .withValue(RawContacts.ACCOUNT_NAME, null)
    .withValue(RawContacts.AGGREGATION_MODE, RawContacts.AGGREGATION_MODE_DISABLED)
    .build());

I appreciate any inputs, be it a workaround or from the API. Thanks!

هل كانت مفيدة؟

المحلول

you can use the information returned from getContentResolver() (which you anyways have to call in order to add ops to the DB. getContentResolver() needs to have a try,catch environment.

...
ContentProviderResult[] res = getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
...
Uri myContactUri = res[0].uri;
int lastSlash = myContactUri.toString().lastIndexOf("/");
int length = myContactUri.toString().length();
int contactID = Integer.parseInt((String) myContactUri.toString().subSequence(lastSlash+1, length));
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top