android - 如何使用 Android native API 获取 Vcard 格式的 Android 联系人

标签 android vcf-vcard

我正在尝试使用 Android Api 读取 VCard 格式的 Android 设备联系人。 我找到了一个相同的链接: Android contatcs vcard API

并尝试编写相同的代码但它不起作用,因为我无法获得查找键:

ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
                null, null, null, null);  
int num = cur.getCount();  // I get 2 , as there are two contacts

String lookupKey = cur.getString(cur.getColumnIndex(Contacts.LOOKUP_KEY));
// The above line gives error : android.database.CursorIndexOutOfBoundsException:
//  Index -1 requested, with a size of 2

Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_VCARD_URI, lookupKey);
AssetFileDescriptor fd = resolver.openAssetFileDescriptor(uri, "r");
FileInputStream fis = fd.createInputStream();
    byte[] b = new byte[(int)fd.getDeclaredLength()];
fis.read(b);
String vCard = new String(b);
sb.append(vCard);

任何人都可以告诉我如何获取上述代码的 lookupkey 或我们可以使用 Android api 获取联系人 VCard 格式的任何其他方法。

最佳答案

给你:

Cursor cursor = context.getContentResolver().query(
                ContactsContract.Contacts.CONTENT_URI, null, null, null, null);

if (cursor != null && cursor.moveToFirst()) {
    try {
        do {
            String lookupKey = cursor.getString(cursor
                    .getColumnIndex(Contacts.LOOKUP_KEY));


            Uri uri = Uri.withAppendedPath(
                    ContactsContract.Contacts.CONTENT_VCARD_URI,
                    lookupKey);
            AssetFileDescriptor fd;
            try {
                fd = context.getContentResolver()
                        .openAssetFileDescriptor(uri, "r");
                FileInputStream fis = fd.createInputStream();
                byte[] b = new byte[(int) fd.getDeclaredLength()];
                fis.read(b);
                String vCard = new String(b);
                Log.i(TAG, vCard);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } while (cursor.moveToNext());
    } finally {
        cursor.close();
    }
}

关于android - 如何使用 Android native API 获取 Vcard 格式的 Android 联系人,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8035841/

相关文章:

vcf-vcard - 是否可以生成绕过 Thunderbird 换行错误的 vcard 2.1?

android - 如何在 Android 中发送带有文件附件的电子邮件

android - 在 com.google.android.gms :play-services-gcm:9. 0.0 中收到任何通知之前安装后关闭应用程序时无法显示 GCM 通知

Android 语音语音识别 : Repeated Calling of SpeechRecognizer. startListening() 在 JB 4.1.2 上失败

java - ACTION_MOVE 未报告正确的 Y 值

Javascript - 在文本区域中中断,但不在段落中中断

java - 使用cardme从一个文件读取多个vcard

调用 vcard.load(conn) 时 Android asmack vcard classcastException

android - 使用搜索栏将数据从主 Activity 传递到 SurfaceView 线程

android - MediaStore.Images.Media.insertImage 在某些设备上抛出权限拒绝