Xamarin android获取地址联系人

时间:2017-10-18 18:36:34

标签: java android xamarin xamarin.android

如何与地址联系?

  var uri = ContactsContract.Contacts.ContentUri;

        string[] projection = {
            ContactsContract.CommonDataKinds.StructuredPostal.InterfaceConsts.Id,
            ContactsContract.CommonDataKinds.StructuredPostal.InterfaceConsts.DisplayName,
            ContactsContract.CommonDataKinds.StructuredPostal.FormattedAddress
        };


        var cursor = Application.Context.ContentResolver.Query(uri, projection, null, null, null);

        var contactList = new List<(string id, string name, string address)>();

        if (cursor.MoveToFirst())
        {
            do
            {
                contactList.Add(
                    (
                        cursor.GetString(cursor.GetColumnIndex(projection[0])),
                        cursor.GetString(cursor.GetColumnIndex(projection[1])),
                        cursor.GetString(cursor.GetColumnIndex(projection[2]))
                    )
                );
            } while (cursor.MoveToNext());
        }

当我尝试这个时,我得到异常说“无效列数据1”我只想要联系人列表+他的地址

1 个答案:

答案 0 :(得分:0)

别名FormattedAddress(或data1)存在于以下提供商处:

  • content://com.android.contacts/data/phones

所以请使用ContactsContract.CommonDataKinds.Phone.ContentUri

var uri = ContactsContract.CommonDataKinds.Phone.ContentUri;
string[] projection = {
    ContactsContract.CommonDataKinds.StructuredPostal.InterfaceConsts.Id,
    ContactsContract.CommonDataKinds.StructuredPostal.InterfaceConsts.DisplayName,
    ContactsContract.CommonDataKinds.StructuredPostal.FormattedAddress
};
var cursor = Application.Context.ContentResolver.Query(uri, projection, null, null, null);
var contactList = new List<(string id, string name, string address)>();
while (cursor.MoveToNext())
{
    contactList.Add(
        (
            cursor.GetString(cursor.GetColumnIndex(projection[0])),
            cursor.GetString(cursor.GetColumnIndex(projection[1])),
            cursor.GetString(cursor.GetColumnIndex(projection[2]))
        )
    );
}