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
edwin
source
to share
Cursor.getCount()
will return 0 for an empty result set.
0
Graham borland
source
to share
I think you are looking for a method getCount()
.
Just check cursor.getCount()==0
for an empty result.
0
Shashank kadne
source
to share
if(cursor.moveToFirst()){
//do your work
}
else{
Toast.makeText(getBaseContext(), "No records yet!", Toast.LENGTH_SHORT).show();
}
0
Moin ahmed
source
to share