CursorIndexOutOfBoundsException Index 0 requested, with size 0

I am trying to get text from a specific row of my database. For this, I made this function

public String getTranslation(long rowId) throws SQLException { String str = null; Cursor mCursor = db.query( true, TABLE_LANGUAGE_FR, new String[] { KEY_ID_INTERFACE_TEXT, KEY_ITEM_NAME,KEY_FORM_LABEL_ID, KEY_FORM_RANK }, KEY_FORM_LABEL_ID + "=" + rowId, null, null, null, null, null ); if (mCursor != null) { mCursor.moveToFirst(); str = mCursor.getString(mCursor.getColumnIndex(KEY_ITEM_NAME)); } return str; } 

and I call it like this:

 db = new DbAdapter(this); db.createDatabase(); db.openDataBase(); String str = db.getTranslation(1706); 

My table looks like this:

enter image description here

I get this error:

 09:32:08.965 307 com.Orange ERROR AndroidRuntime Caused by: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0 09:32:08.965 307 com.Orange ERROR AndroidRuntime at android.database.AbstractCursor.checkPosition(AbstractCursor.java:580) 09:32:08.965 307 com.Orange ERROR AndroidRuntime at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:214) 09:32:08.965 307 com.Orange ERROR AndroidRuntime at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:41) 09:32:08.965 307 com.Orange ERROR AndroidRuntime at com.Orange.Database.DbAdapter.getTranslation(DbAdapter.java:141) 09:32:08.965 307 com.Orange ERROR AndroidRuntime at com.Orange.Authentication.onCreate(Authentication.java:32) 

Why am I getting this error? What am I doing wrong here?

Thanks in advance.

+6
source share
3 answers

It would seem that you have an emtpy cursor. Instead of checking if this is a null check

 if(mCursor.getCount() > 0) { //do stuff } 

try deleting your condition to make sure that you really get the data when you run the select statement. If you still don’t get anything, you may have a typo in your table names or you could not connect / create the database / table.

 Cursor mCursor = db.query("sys_interface_text", new String[] { "id_interface_text", "item_name","form_label_id", "form_rank"}, "form_label_id = 1706", null, null, null, null); 
+25
source

Try using

 while(cursor.moveToNext()) { if(cursor.isFirst()) { //Your code goes here in your case return mCursor.getString(mCursor.getColumnIndex(KEY_ITEM_NAME)); } } finaly { if(mCursor!= null) { mCursor.close(); } } 
+1
source

try changing this line

 Cursor mCursor = db.query(true, TABLE_LANGUAGE_FR, new String[] { KEY_ID_INTERFACE_TEXT, KEY_ITEM_NAME,KEY_FORM_LABEL_ID, KEY_FORM_RANK}, KEY_FORM_LABEL_ID + "=" + rowId, null, null, null, null, null); 

 Cursor mCursor = db.query(TABLE_LANGUAGE_FR, new String[] { KEY_ID_INTERFACE_TEXT, KEY_ITEM_NAME,KEY_FORM_LABEL_ID, KEY_FORM_RANK}, KEY_FORM_LABEL_ID + "=" + rowId, null, null, null, null); 

and also add this if condition

  return str; 
0
source

Source: https://habr.com/ru/post/919303/


All Articles