Khaled Mohamed
Khaled Mohamed

Reputation: 217

Cursor Exception

I have created a database and i want to retrieve some data from the database by using the cursor by i always get this error

04-19 20:02:56.747: E/AndroidRuntime(301): android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1
04-19 20:02:56.747: E/AndroidRuntime(301):  at android.database.AbstractCursor.checkPosition(AbstractCursor.java:580)
04-19 20:02:56.747: E/AndroidRuntime(301):  at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:214)
04-19 20:02:56.747: E/AndroidRuntime(301):  at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:41)

here is the code of the function

public double getlatitude(String[] i,int x) {
        // TODO Auto-generated method stub
        String[] columns = new String[] { KEY_SQUAREID, KEY_SQUARELATITUDE, KEY_SQUARENAME,
                KEY_SQUARELONGITUDE
                 };

    Cursor c;
      c=ourDatabase.query("squares", columns,"squarename=?",i, null, null, null);

      String latitude = null;
        if (c.moveToFirst()) {
             latitude=c.getString(0);
        }

        double latitude_double=Double.parseDouble(latitude);
        return latitude_double;
    }

Upvotes: 0

Views: 127

Answers (4)

Shubhayu
Shubhayu

Reputation: 13552

Whenever you are dealing with Cursors, ALWAYS check for null and check for moveToFirst() without fail, if you want to avoid weird crashes in the future.

if( c != null ){
    if( c.moveToFirst() ){
        //Do your stuff
    }
}

//After finishing always close the cursor.
c.close();

Upvotes: 0

waqaslam
waqaslam

Reputation: 68167

I think the problem is here:

latitude=c.getString(0);

Change it to:

latitude = c.getString(c.getColumnIndex("column_name"));

and also dont forget to close your cursor before returning value by calling c.close();

Upvotes: 0

Raam
Raam

Reputation: 10866

The exception likely occurred because your cursor is empty (there may have been no match). To avoid this make sure that you check whether the cursor is empty or not, if it is empty then you should not try to access it. And if it is not empty, you should check the max row count and make sure that you don’t access to any row that is equal or higher than the max row count. See the code below:

if ( c != null && c.getCount() > 0 ) {
    if (c.moveToFirst()) {
        do {

            // do something here

        } while (c.moveToNext());
    }
    c.close();
}

Upvotes: 0

Gaurav Agarwal
Gaurav Agarwal

Reputation: 19102

Try this

if(c.getCount() > 0) {
   c.moveToFirst();
   for(int i=0;i<c.getCount();i++) {
     //do your logic here
   }
}

Upvotes: 1

Related Questions