Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0

I am using custom adapter extending cursor adapter for displaying data in listview, to display particular phone number i have passed the id to a method in database class but it is showing

errorandroid.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0  

while placing debugger in the the method it is not going after the line

num = cursor.getString(cursor.getColumnIndex("ContactNumber")); 

Can any one help me to solve it. This is the code:

public String getNumberFromId(int id)  {     String num;     db= this.getReadableDatabase();     Cursor cursor = db.query(scheduletable, new String[] { "ContactNumber" },"_id="+id, null, null, null, null);     cursor.moveToFirst();     num = cursor.getString(cursor.getColumnIndex("ContactNumber"));      cursor.close();     db.close();     return num; } 
like image 499
user181291 Avatar asked Apr 20 '12 10:04

user181291


2 Answers

Whenever you are dealing with Cursors, ALWAYS check for null and check for moveToFirst() without fail.

if( cursor != null && cursor.moveToFirst() ){     num = cursor.getString(cursor.getColumnIndex("ContactNumber"));     cursor.close();  } 

Place logs appropriately to see whether it is returning null or an empty cursor. According to that check your query.

Update Put both the checks in a single statement as mentioned by Jon in the comment below.

Update 2 Put the close() call within the valid cursor scope.

like image 192
Shubhayu Avatar answered Oct 04 '22 23:10

Shubhayu


try this.. this will avoid an Exception being thrown when the cursor is empty..

if(cursor != null && cursor.moveToFirst()){     num = cursor.getString(cursor.getColumnIndex("ContactNumber"));      cursor.close(); } 
like image 27
ngesh Avatar answered Oct 05 '22 01:10

ngesh