Search code examples
androidindexoutofboundsexceptionandroid-cursoradapter

Cursor index out of bound error


I'm experimenting with the database and here I've not used the helper class but added the db functions within the activity. I've got a index out of bound error while trying to select a column from the obtained row.

Specifically

android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1 error.

MainActivity

public class MainActivity extends AppCompatActivity {

SQLiteDatabase db;
private EditText foldernameEditText;
private ListView folderlistview;
private TextView mEmptyStateTextView;
ListViewCursorAdapter listViewCursorAdapter;
final String mfoldertable = "foldertable";
final String mtitletable = "titletable";
TextView transfer;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    db = openOrCreateDatabase("mainDB", Context.MODE_PRIVATE, null);
    db.execSQL("CREATE TABLE IF NOT EXISTS " + mfoldertable + "(_id integer primary key autoincrement, folder text collate NOCASE, UNIQUE(folder))");
    db.execSQL("CREATE TABLE IF NOT EXISTS "+mtitletable+ "(_id integer primary key autoincrement,id1 integer, title text, FOREIGN KEY(id1) REFERENCES "+mfoldertable+"(_id))");
    //db.execSQL("Drop table "+mfoldertable+"");
    //db.execSQL("Drop table "+mtitletable+"");
    Cursor c = db.rawQuery("SELECT * FROM " + mfoldertable + "", null);
    listViewCursorAdapter = new ListViewCursorAdapter(this, c);
    folderlistview = (ListView) findViewById(R.id.folderlistview);
    mEmptyStateTextView = (TextView) findViewById(R.id.empty_view);
    folderlistview.setAdapter(listViewCursorAdapter);
    folderlistview.setEmptyView(mEmptyStateTextView);
    foldernameEditText = (EditText) findViewById(R.id.foldername);
    Button enterFolderButton = (Button) findViewById(R.id.enterFolderButton);
    enterFolderButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            try {
                db.execSQL("INSERT INTO "+mfoldertable+"(folder) VALUES('"+ foldernameEditText.getText().toString() +"')");
            } catch (SQLiteConstraintException exception) {
                Toast.makeText(getApplicationContext(), "This folder already exists", Toast.LENGTH_SHORT).show();
            }
            foldernameEditText.setText("");
            Cursor d = db.rawQuery("SELECT * FROM " + mfoldertable + "", null);
            listViewCursorAdapter.swapCursor(d);
        }
    });

    folderlistview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            Intent intent = new Intent(MainActivity.this, TitleList.class);
            Bundle bundle = new Bundle();
            transfer = (TextView) view.findViewById(R.id.list_item_folder_text_view);
            String stuff = transfer.getText().toString();
            bundle.putString("hello", stuff);
            Cursor f=db.rawQuery("SELECT * FROM "+mfoldertable+" where folder='"+stuff+'"",null);
            //Log.e("helloerror",f.getString(f.getColumnIndexOrThrow("_id")));
            bundle.putInt("int",f.getInt(f.getColumnIndexOrThrow("_id")));

            //bundle.putInt("int",1);
            intent.putExtras(bundle);
            startActivity(intent);
        }
    });
}

}

Cursor f is the line pointing to the error. Can't figure out why. Although the auto increment variable displays properly on the appropriate text view next to the entered folder, I'm not able to obtain it.


Solution

  • android.database.CursorIndexOutOfBoundsException

    This Exception denotes that you are trying to access the cursor with an invalid index. Make sure you are calling moveToFirst() method as soon as you get your cursor object. This will return a boolean denoting whether your cursor has any data or not and set your cursor to first element if it does have any data.

    Replace this:

    bundle.putInt("int",f.getInt(f.getColumnIndexOrThrow("_id")));
    

    With this :

    if (f != null && f.moveToFirst()) {
           bundle.putInt("int",f.getInt(f.getColumnIndexOrThrow("_id")));
    }
    

    For further help, refer this answer : android.database.CursorIndexOutOfBoundsException