0

In the main activity I am trying to check when the app gets open if the app database exist or not. This is because I want to get a chance to create the database and insert all the needed records on the very first run only.

But it's not working with me, it give me this error:

..Caused by: android. database. CursorindexOutOfBoundsException: Index 0 requested, with a size of 0

My first thought is that the above exception/error is not SQLiteException or I don't know exactly what I am missing.

Here is my code:

    DBAdapter dbCheck = new DBAdapter(this);
    boolean dbStatus;
    String strData;
    try { 
        dbCheck.open(); 
        Cursor tblCheck = dbCheck.getThis_tblData(10); //get record no 10 - random number
        strData = tblCheck.getString(5);   // get the value of a field in the table
        tblCheck.close();
        dbCheck.close();
        System.out.println("<---> Db found ");
    } catch (SQLiteException e) { 
        //database doesn't exist yet. Create it.
        System.out.println("<---> Db not found ");
    Intent MakeDB = new Intent(MainActivity.this, com.kjsoft.tre.InsertData.class);
    StartActivity(MakeDB);
    } 

Thanks everyone for your help!

MPelletier
  • 16,256
  • 15
  • 86
  • 137
Great Dreams
  • 91
  • 3
  • 13

2 Answers2

0

This particular exceptions happens in the generic Cursor class, so it's not an SQLiteException.

You could change the type in the catch statement, like Nambari said, but it is a better idea to create an SQLiteOpenHelper class to manage the creation of the DB (and updates, if your app ever changes).

CL.
  • 173,858
  • 17
  • 217
  • 259
0

replace the following line in you code:

Cursor tblCheck = dbCheck.getThis_tblData(10);

with the following:

Cursor tblCheck = dbCheck.getThis_tblData(10);
if ((tblCheck != null) && (tblCheck.getCount() > 0)) {
    tblCheck.moveToNext();
    strData = tblCheck.getString(5);
}

the cursor initial position is always just before the first row, so you have to move it to the next step (the first row) and then access your data. and of course, you have to check if it is not null.

kdehairy
  • 2,630
  • 22
  • 27