3

在我的应用程序(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));}

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

“无法从具有 1 行 29 列的 CursorWindow 读取第 0 行第 -1 列。”

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

4

1 回答 1

3

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

清单.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();
                    }
                }
            }
于 2012-12-08T13:54:10.633 回答