ANDROID SQLITE checks for the existence of table data
I want to check if my table has records. Here's what I've tried:
if( cursor != null ){
cursor.moveToFirst();
if (cursor.getInt(0) == 0) {
Toast.makeText(getBaseContext(), "No records yet!", Toast.LENGTH_SHORT).show();
}
}
Logcat says:
CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
Any help is appreciated. Thank you.
+3
user1410081
source
to share
4 answers
try it
cursor.getCount();
it will return if the cursor fetch data, if it gives 0 then no data
So
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;
}
Note: even if you check if( cursor != null )
, the cursor will not return null after any query is executed, so do that to check the amount of data in the cursor after that
+1
source to share