質問

how can I retrieve a single contact and some associated data (e.g. emails, phonenumbers, addresses...) by its id/lookupkey?

This is the code I use to add contacts (actually its from the internet and is working for me).

// Asking the Contact provider to create a new contact
    try {
        result = this.context.getContentResolver().applyBatch(
                ContactsContract.AUTHORITY, ops);
    } catch (Exception e) {
        e.printStackTrace();
        Toast.makeText(this.context, "Exception: " + e.getMessage(),
                Toast.LENGTH_SHORT).show();
    }

    Uri myContactUri = result[0].uri;
    int lastSlash = myContactUri.toString().lastIndexOf("/");
    int length = myContactUri.toString().length();
    int contactID = Integer.parseInt((String) myContactUri.toString()
            .subSequence(lastSlash + 1, length));

    return contactID;

Now I want to fetch this new contact. How do I do it? All I came up with is this:

    ContentResolver content = context.getContentResolver();

    String[] projection = { Data.LOOKUP_KEY, Data.MIMETYPE,
            ContactsContract.Contacts._ID,
            ContactsContract.Contacts.DISPLAY_NAME,
            ContactsContract.CommonDataKinds.Phone.NUMBER,
            ContactsContract.CommonDataKinds.Email.ADDRESS };

    // Defines the selection clause
    String selection = Data.LOOKUP_KEY + " = ?";

    // Defines the sort order
    String sortOrder = Data.LOOKUP_KEY;

    String[] args = {"2400"};

    Cursor cursor = content.query(Data.CONTENT_URI, projection, selection,
            args, sortOrder);

When I remove the selection I get all contacts+all their data. So I looked up the key 2400 in my case and wanted to fetch this contact by its lookupkey. Well, does not work. cursor.getCount() return 0.

Any ideas?

役に立ちましたか?

解決

My solution now is to use to following:

    String[] projection = { Data.MIMETYPE,
            ContactsContract.Contacts._ID,
            ContactsContract.Contacts.DISPLAY_NAME,
            ContactsContract.CommonDataKinds.Phone.NUMBER,
            ContactsContract.CommonDataKinds.Email.ADDRESS };

    // Defines the selection clause
    String selection = ContactsContract.Data.RAW_CONTACT_ID + "=?";

    // Defines the sort order
    String sortOrder = Data.LOOKUP_KEY;

    String[] args = { id+"" };

    Cursor cursor = content.query(Data.CONTENT_URI, projection, selection,
            args, sortOrder);

Sort order doesnt matter, but I use the RAW_CONTACT_ID, which works well!

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top