开发者

FileNotFoundException while trying to convert contacts to Vcard

开发者 https://www.devze.com 2022-12-25 00:59 出处:网络
I m trying to convert the contacts on emulator to VCard format using the codebelow AssetFileDescriptor afd =openAssetFileDescriptor(Contacts.CONTENT_VCARD_URI ,\"r\")

I m trying to convert the contacts on emulator to VCard format using the code below

AssetFileDescriptor afd =openAssetFileDescriptor(Contacts.CONTENT_VCARD_URI ,"r")

The stack Trace says java.io.FileNotFoundException No file at content://com.android.contacts/contacts/as_vcard

Do we need to attach a file开发者_如何学Go to the URI ? Is there some other way to convert Contacts to Vcard in Android?


You have to iterate through the contact db and call openAssetFileDescriptor() on each one individually. The important part is that you have to use the lookup key for each contact and append it to the CONTENT_VCARD_URI using the URI.withAppendedPath() method.


I just stumbled with this one too. Here is a way to do it. 1st let the user pick his contact or get the contactUri another way.

After you have the contactUri you lookup the lookup_key and after that you can retrieve the vcard. Here is the code I used after i got the contactUri (kind of copy paste from different functions, but should work).

Cursor cursor = resolver.query(contactUri, new String[] {
    Contacts.LOOKUP_KEY
}, null, null, null);
FileInputStream input = null;

try {
    if (cursor.moveToFirst()) {
        return cursor.getString(0);
    } else return;

    AssetFileDescriptor afd = context.getContentResolver().openAssetFileDescriptor(
            Uri.withAppendedPath(Contacts.CONTENT_VCARD_URI, lookupKey), "r");
    input = afd.createInputStream();

    int ch;
    StringBuffer strContent = new StringBuffer("");
    while ((ch = input.read()) != -1)
        strContent.append((char) ch);

    Log.d(TAG, strContent.toString());
} finally {
    cursor.close();
    if (input != null) {
        input.close();
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消