Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ANDROID SQLITE check if table has data

Tags:

android

sqlite

I'd like 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. Thanks.


1 Answers

Try this

cursor.getCount();

it will return if cursor retrieve data count if this give 0 then there is 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 though you check if( cursor != null ) cursor will not return null value after doing any query, so do this to check the data count in cursor after that

like image 87
edwin Avatar answered May 18 '26 12:05

edwin