【问题标题】:Getting Android Contacts Cursor Exception获取 Android 联系人光标异常
【发布时间】:2013-12-15 09:44:35
【问题描述】:

我正在尝试获取用户选择的联系人号码。问题是,每当从列表中选择一个联系人时,它都会抛出这个异常:

android.database.CursorIndexOutOfBoundsException: 请求索引 0,大小为 0

任何联系人都会出现这种情况,即使是拥有多个电话号码的联系人。

为我打开联系人列表的唯一示例:

Pick a Number and Name From Contacts List in android app

How to read contacts on Android 2.0

Android contacts database giving me an exception

它们都对我产生相同的错误。

我的代码:

调用意图

public void pickPerson(View V)
{
    Intent intent = new Intent(Intent.ACTION_PICK,
                               ContactsContract.Contacts.CONTENT_URI);
    intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
    startActivityForResult(intent, PICK_CONTACT);
}

获取电话号码

//Declcared earlier
static final int PICK_CONTACT=1;

@Override
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 =  getContentResolver().query(contactData, null, null, null, null);
                if (c.moveToFirst()) 
                {
                    String id =c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts._ID));

                    String hasPhone =c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));

                    if (hasPhone.equalsIgnoreCase("1")) 
                    {
                        Cursor phones = getContentResolver().query( 
                              ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null, 
                              ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ id, 
                              null, null);
                        phones.moveToFirst();
                        String cNumber = phones.getString(phones.getColumnIndex(PhoneLookup.NUMBER));
                        phone.setText(cNumber); //EditText view
                    }
                }
            }
            break;
        }
    }
}

日志猫:

11-29 12:35:17.770: E/AndroidRuntime(26254): FATAL EXCEPTION: main
11-29 12:35:17.770: E/AndroidRuntime(26254): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { dat=content://com.android.contacts/data/1051 flg=0x1 }} to activity {somebadger.textspammer/somebadger.textspammer.Main}: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
11-29 12:35:17.770: E/AndroidRuntime(26254):    at android.app.ActivityThread.deliverResults(ActivityThread.java:3208)
11-29 12:35:17.770: E/AndroidRuntime(26254):    at android.app.ActivityThread.handleSendResult(ActivityThread.java:3251)
11-29 12:35:17.770: E/AndroidRuntime(26254):    at android.app.ActivityThread.access$1200(ActivityThread.java:143)
11-29 12:35:17.770: E/AndroidRuntime(26254):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1289)
11-29 12:35:17.770: E/AndroidRuntime(26254):    at android.os.Handler.dispatchMessage(Handler.java:99)
11-29 12:35:17.770: E/AndroidRuntime(26254):    at android.os.Looper.loop(Looper.java:137)
11-29 12:35:17.770: E/AndroidRuntime(26254):    at android.app.ActivityThread.main(ActivityThread.java:4953)
11-29 12:35:17.770: E/AndroidRuntime(26254):    at java.lang.reflect.Method.invokeNative(Native Method)
11-29 12:35:17.770: E/AndroidRuntime(26254):    at java.lang.reflect.Method.invoke(Method.java:511)
11-29 12:35:17.770: E/AndroidRuntime(26254):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1004)
11-29 12:35:17.770: E/AndroidRuntime(26254):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:771)
11-29 12:35:17.770: E/AndroidRuntime(26254):    at dalvik.system.NativeStart.main(Native Method)
11-29 12:35:17.770: E/AndroidRuntime(26254): Caused by: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
11-29 12:35:17.770: E/AndroidRuntime(26254):    at android.database.AbstractCursor.checkPosition(AbstractCursor.java:418)
11-29 12:35:17.770: E/AndroidRuntime(26254):    at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:136)
11-29 12:35:17.770: E/AndroidRuntime(26254):    at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:50)
11-29 12:35:17.770: E/AndroidRuntime(26254):    at android.database.CursorWrapper.getString(CursorWrapper.java:114)
11-29 12:35:17.770: E/AndroidRuntime(26254):    at somebadger.textspammer.Main.onActivityResult(Main.java:76)
11-29 12:35:17.770: E/AndroidRuntime(26254):    at android.app.Activity.dispatchActivityResult(Activity.java:5344)
11-29 12:35:17.770: E/AndroidRuntime(26254):    at android.app.ActivityThread.deliverResults(ActivityThread.java:3204)

【问题讨论】:

  • 在此处添加您的 logcat 消息..

标签: android android-contacts


【解决方案1】:

你可以试试这个String cNumber = phones.getString(phones.getColumnIndex("data1"));

【讨论】:

    【解决方案2】:

    试试这个...

    public class ReadContacts extends AsyncTask<Void, Void, Void>{
    
        private ListView contactsList;
    
        private Context cntx;
        private Constant constants;
    
        static final String[] CONTACTS_SUMMARY_PROJECTION = new String[] {
            Contacts._ID, // 0
            Contacts.DISPLAY_NAME, // 1
            Contacts.STARRED, // 2
            Contacts.TIMES_CONTACTED, // 3
            Contacts.CONTACT_PRESENCE, // 4
            Contacts.PHOTO_ID, // 5
            Contacts.LOOKUP_KEY, // 6
            Contacts.HAS_PHONE_NUMBER, // 7
        };
    
        private long contactId;
        private String display_name;
        private String phoneNumber;
    
        private ArrayList<ContactsWrapper>contactWrap = new ArrayList<ContactsWrapper>();
        private HashMap<Long, ArrayList<ContactsWrapper>>map = new HashMap<Long, ArrayList<ContactsWrapper>>();
    
        private ContactsAdapter adapter;
    
        private DataController controller;
    
        public ReadContacts(Context cntx, ListView contactList) {
            // TODO Auto-generated constructor stub
            this.cntx = cntx;
            constants = new Constant();
            this.contactsList = contactList;
    
            controller = DataController.getInstance(); 
        }
    
        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();
            if(!(controller.contactWrapper.size()>0))
                 constants.displayProgressDialog(cntx, "Loading Contacts...", "Please Wait");
        }
    
        @Override
        protected Void doInBackground(Void... params) {
            // TODO Auto-generated method stub
    
            if(!(controller.contactWrapper.size()>0))
            {
            try {
                String select = "((" + Contacts.DISPLAY_NAME + " NOTNULL) AND ("
                        + Contacts.HAS_PHONE_NUMBER + "=1) AND ("
                        + Contacts.DISPLAY_NAME + " != '' ))";
    
                Cursor c = cntx.getContentResolver().query(Contacts.CONTENT_URI, CONTACTS_SUMMARY_PROJECTION, select,
                        null, Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
    
                int colorcounter = 0;
                String[] colorcounter_array = { "#91A46B", "#8BB6B5", "#CAA973", "#8DA6C8","#D19B8D"};
    
                int color_string;
                for(int i=0;i<c.getCount();i++)
                {
    //              contactWrap.clear();
                    try {
                        contactId = 0;
                        String hasPhone = "";
                        display_name = "";
                        phoneNumber = "";
    
                        c.moveToPosition(i);
    
                        contactId =  c.getLong(0);
                        display_name = c.getString(1);
                        hasPhone = c.getString(7);
    
                        if (hasPhone.equalsIgnoreCase("1"))
                            hasPhone = "true";
                        else
                            hasPhone = "false" ;
    
                        if (Boolean.parseBoolean(hasPhone)) 
                        {
                            Cursor phones = cntx.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactId,null, null);
                            while (phones.moveToNext()) 
                            {
                                int indexPhoneType = phones.getColumnIndexOrThrow(Phone.TYPE);
                                String phoneType =  phones.getString(indexPhoneType);
    
                                phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)); 
    
                                String lookupKey = phones.getString(phones.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
    
                                if (colorcounter < 5) 
                                {
                                    color_string =Color.parseColor(colorcounter_array[colorcounter]);
                                    colorcounter++;
                                } else {
                                    colorcounter = 0;
                                    color_string =Color.parseColor(colorcounter_array[colorcounter]);
                                    colorcounter++;
                                }
                                contactWrap.add(new ContactsWrapper(contactId, display_name, phoneNumber,lookupKey,false,color_string));
                            }
    //                      map.put(contactId, new ArrayList<ContactsWrapper>(contactWrap));
                            phones.close();
                        }
                    } catch (Exception e) {
    
                        e.printStackTrace();
                    }  
                }
                controller.contactWrapper = contactWrap;
            }
            catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
            }
            }
    
            return null;
        }
    
        @Override
        protected void onPostExecute(Void result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            constants.dismissDialog();
    
            adapter = new ContactsAdapter(cntx);
            contactsList.setAdapter(adapter);
        }
    
    }
    

    这是我的联系人包装类

    public class ContactsWrapper {
    
    private long contactId;
    private String displayName,displayNumber,lookUp;
    public boolean checked = true;
    int color_string;
    
    public ContactsWrapper(long contactId, String displayName, String displayNumber, String lookUp, boolean checked,int color_string) {
        // TODO Auto-generated constructor stub
        this.contactId = contactId;
        this.displayName = displayName;
        this.displayNumber = displayNumber;
        this.lookUp = lookUp;
        this.checked = checked;
        this.color_string =color_string;
    }
    
    public String getLookUp() {
        return lookUp;
    }
    
    public int getColor_string() {
        return color_string;
    }
    
    public boolean isChecked() {
        return checked;
    }
    
    public long getContactId() {
        return contactId;
    }
    
    public String getDisplayName() {
        return displayName;
    }
    
    public String getDisplayNumber() {
        return displayNumber;
    }
    
    public void setChecked(boolean checked) {
        this.checked = checked;
    }
    }
    

    【讨论】:

    • 我将如何使用它?我对安卓编程比较陌生。但是当我使用ReadContacts类时,eclipse找不到Constants、DataController和ContactsAdapter类。
    猜你喜欢
    • 2013-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-16
    • 2014-01-21
    • 1970-01-01
    相关资源
    最近更新 更多