【问题标题】:Issue in Adding Cursor Values to ArrayList将光标值添加到 ArrayList 的问题
【发布时间】:2013-08-20 21:02:38
【问题描述】:

我正在尝试查询默认电话内容提供商的电话号码并将由此获得的值存储到 ArrayList ar = new ArrayList(); 光标 cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);

    if (cur.getCount() > 0){

        while (cur.getCount() > 0){
            while(cur.moveToNext()){
                //unique id
                String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
                //number corresponding to the id
                String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                //lets check if this guy even has a number saved
                if(Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0){
                    //Query here
                    //Get the phone numbers!
                    Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                            ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=?",
                            new String[]{id},null);
                    while(pCur.moveToNext()){
                        ar.add((pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER))));
                        }
                    Log.d("String Report", ar.get(5));
                    pCur.close();
                }

但是,这会在 Log.d 方法中给出数组越界错误。由于某种原因,只有一个值被存储在内部,即我只得到 ar.get(0) 作为有效输出。我犯了什么错误??

【问题讨论】:

    标签: android


    【解决方案1】:

    之后

    Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
    

    你必须这样做

    cur.moveToNext();
    

    还有

    pCur.moveToNext();
    

    在尝试使用之前!

    这会将光标移动到第一个元素

    【讨论】:

    • 我已经这样做了,实际上我将 pCur.moveToNext 放在一个 while 循环中,以从内容提供者那里获取不同的数字,这也可以。但是,在将它与 ArrayList 一起使用时,arraylist 并没有按应有的方式添加值。为什么?
    • 尝试在 Log.d 中使用 pCur.getCount() 来查看光标中有多少元素。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-24
    • 1970-01-01
    • 2015-03-30
    • 1970-01-01
    • 2021-02-22
    • 1970-01-01
    相关资源
    最近更新 更多