Android联系人列表获取地址

时间:2012-12-08 13:16:55

标签: android cursor uri contactscontract

在我的应用程序(android 4.0)中,我需要从联系人中检索地址。我使用了另一篇文章中提供的解决方案:

Uri contactData = data.getData();
Cursor c =  managedQuery(contactData, null, null, null, null);
    if (c.moveToFirst()) {
        String city = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.CITY));}

但是当我尝试执行此操作时,我收到错误:

“无法从CursorWindow中读取第0行第-1列,其中包含1行,29列。 “

我在这里做错了什么?他为什么不找到城市专栏?

1 个答案:

答案 0 :(得分:3)

好的,解决了,得到了一些愚蠢的错误...... 这是工作代码:

的manifest.xml:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="androidlab.exercise4_1"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk android:minSdkVersion="14" />
<uses-permission android:name="android.permission.READ_CONTACTS"/> ...

代码:

Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType(ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_TYPE); 
startActivityForResult(intent, PICK_CONTACT);




public void onActivityResult(int reqCode, int resultCode, Intent data) {
    super.onActivityResult(reqCode, resultCode, data);

    switch (reqCode) {
        case (PICK_CONTACT) :
            if (resultCode == Activity.RESULT_OK) {
                Uri contactData = data.getData();
                Cursor c =  managedQuery(contactData, null, null, null, null);
                if (c.moveToFirst()) {
                    try{
                        //String street = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.STREET));//ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS));
                        //String city = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.CITY));
                        //String postcode = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE));
                        //String country = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY));
                        String street = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS));
                    }
                    catch(Exception e){
                        errorDialog.show();
                    }
                }
            }