1

我在收件箱中搜索短信时收到cursor index out of bounds “请求索引 0:大小为 0”错误。我编写了以下代码:

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub              
            Cursor cursor = getContentResolver().query(Uri.parse("content://sms/inbox"), null, null, null, null);
            cursor.moveToFirst();
            do{

               String msgData = "";
               for(int idx=0;idx<cursor.getColumnCount();idx++)
               {
                   msgData += " " + cursor.getColumnName(idx) + ":" + cursor.getString(idx);
                   Toast.makeText(getApplicationContext(), msgData, Toast.LENGTH_LONG).show();
               }
            }while(cursor.moveToNext());
        }
    });  
 }
4

4 回答 4

1

只需检查您的 cursor.moveToNext() 如下:

if(cursor.moveToNext())
{
    while(!cursor.isAfterLast())
    {
         //do your job.
         cursor.moveToNext();
    }
}

出现问题是因为您正在使用 do while 循环甚至没有检查游标是否有任何行

于 2013-02-22T06:40:27.850 回答
1
Cursor cursor = getContentResolver().query(Uri.parse("content://sms/inbox"), null, null, null, null);
       if ( cursor.getCount() > 0 )
          for(int i=0;i<cursor.getCount();i++)
          {
              cursor.moveToPosition(i);

           String msgData = "";
           for(int idx=0;idx<cursor.getColumnCount();idx++)
           {
               msgData += " " + cursor.getColumnName(idx) + ":" + cursor.getString(idx);
               Toast.makeText(getApplicationContext(), msgData, Toast.LENGTH_LONG).show();
           }

        }else
           Toast.makeText(getApplicationContext(), "No message was found in device", Toast.LENGTH_SHORT).show();
于 2013-02-22T06:33:02.537 回答
1

在调用 Cursor 上的任何方法之前,您需要检查您的查询是否返回结果。你可以通过检查来做到这一点cursor.getCount() > 0

于 2013-02-22T06:31:25.157 回答
1

您应该检查的返回值cursor.moveToFirst()或简单地检查cursor.getCount()

于 2013-02-22T06:31:37.080 回答