ANDROID SQLITE检查表是否有数据
我想检查一下我的桌子是否有记录。以下是我尝试过的:ANDROID SQLITE检查表是否有数据,android,sqlite,Android,Sqlite,我想检查一下我的桌子是否有记录。以下是我尝试过的: if( cursor != null ){ cursor.moveToFirst(); if (cursor.getInt(0) == 0) { Toast.makeText(getBaseContext(), "No records yet!", Toast.LENGTH_SHORT).show(); } } Logcat说: CursorIndexOutOfBou
if( cursor != null ){
cursor.moveToFirst();
if (cursor.getInt(0) == 0) {
Toast.makeText(getBaseContext(), "No records yet!", Toast.LENGTH_SHORT).show();
}
}
Logcat说:
CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
感谢您的帮助。谢谢
Cursor.getCount()
将为空结果集返回0。我认为您正在寻找方法getCount()
只需检查cursor.getCount()==0即可获得空结果。试试这个
if(cursor.moveToFirst()){
//do your work
}
else{
Toast.makeText(getBaseContext(), "No records yet!", Toast.LENGTH_SHORT).show();
}
cursor.getCount();
如果游标检索数据计数,则返回该值。如果该值为0,则表示没有数据
所以
注意:即使您检查
if(cursor!=null)
cursor在执行任何查询后都不会返回null值,因此执行此操作以检查cursor中的数据计数,然后测试moveToFirst或cursor.getCount的结果(即光标中有多少条记录)
if(cursor != null && cursor.getCount()>0){
cursor.moveToFirst();
//do your action
//Fetch your data
}
else {
Toast.makeText(getBaseContext(), "No records yet!", Toast.LENGTH_SHORT).show();
return;
}