简体   繁体   English

如何检索单个联系人

[英]How to retrieve a single contact

how can I retrieve a single contact and some associated data (eg emails, phonenumbers, addresses...) by its id/lookupkey? 如何通过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. 因此,我查找了本例中的密钥2400,并希望通过其lookupkey来获取此联系人。 Well, does not work. 好吧,不起作用。 cursor.getCount() return 0. cursor.getCount()返回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! 排序顺序无关紧要,但是我使用RAW_CONTACT_ID,效果很好!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM