问题
I'm trying to get all of my contacts as vCard.
So this is my code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
if (cur.getCount() > 0) {
//cur.moveToFirst();
while (cur.moveToNext()) {
try{
String lookupKey =
cur.getString(cur.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
Uri uri =
Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_VCARD_URI,
lookupKey);
AssetFileDescriptor fd =
this.getContentResolver().openAssetFileDescriptor(uri, "r");
FileInputStream fis = fd.createInputStream();
byte[] buf = new byte[(int)fd.getDeclaredLength()];
if (0 < fis.read(buf))
{
String vCard = new String(buf);
System.out.println("The vCard value is " + vCard);
}
fis.close();
}
catch(Exception e)
{
System.out.println(e.getStackTrace());
}
}
}
cur.close();
System.out.println(cur.getCount());
}
}
This gives me almost all of the contacts, but it doesn't return some contacts that contains some special characters, in Portuguese we say "mãe" (mom) and this code doesn't recognize it. All other names like "António" doesn't appear to.
I'm stuck in this for a long time.
回答1:
The best way to get a VCard is to write your own function to create a VCard.The way which you are using has problems when Contacts are not in English. Fetch all the fields of a contact manually and write it to your VCard file.
Take a look at https://code.google.com/p/android-vcard/ for reading from and writing to a VCard
回答2:
If you want to use the "built in" android classes to generate your vcards, then it's quite simple.
public ArrayList<String> getContactsAsVcards()
{
ArrayList<String> vcards = new ArrayList<String>();
VCardComposer vCardComposer = new VCardComposer(context);
vCardComposer.init();
do {
String vCard = vCardComposer.createOneEntry();
vcards.add(vCard);
} while (!vCardComposer.isAfterLast());
return vcards;
}
You just have to download the android classes from the android source code and add them to your project under the correct package name, com.android.vcard
and com.android.vcard.exception
.
You can download the classes from here. That is for Android 4.4 r1 version.
Probably to late for you but in case someone is looking for a more robust and nice way to get the vcards from their contact list and letting android internally take care of all the work, this is it IMO.
来源:https://stackoverflow.com/questions/8566363/getting-all-contacts-as-vcard-in-android