当我在收件箱中搜索短信时,我收到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());
}
});
}
答案 0 :(得分:1)
在调用Cursor上的任何方法之前,您需要检查查询是否返回结果。您可以通过选中cursor.getCount() > 0
。
答案 1 :(得分:1)
您应该检查cursor.moveToFirst()
的返回值,或者只需查看cursor.getCount()
答案 2 :(得分: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();
答案 3 :(得分:1)
只需检查你的cursor.moveToNext(),如下所示:
if(cursor.moveToNext())
{
while(!cursor.isAfterLast())
{
//do your job.
cursor.moveToNext();
}
}
问题是因为你使用do while循环而甚至没有检查 光标是否有任何行。