3

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
  • 1
    test the result of moveToFirst, or of cursor.getCount (that how many records are in your cursor) Commented Jan 28, 2013 at 16:47

4 Answers 4

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

Cursor.getCount() will return 0 for an empty result set.

Comments

0

I think you are looking for the method getCount().

Just check cursor.getCount()==0 for empty result.

Comments

0
if(cursor.moveToFirst()){ //do your work } else{ Toast.makeText(getBaseContext(), "No records yet!", Toast.LENGTH_SHORT).show(); } 

Comments