-2

InfoAPI.java

When I click Save button, it crashed. How can I fix this?

public long insertTimeSheet(String name,String weather,String date,String status)
    {
        database=dbHelper.getWritableDatabase();
        ContentValues values=new ContentValues();
        values.put(MyDatabaseHelper.Name,name);
        values.put(MyDatabaseHelper.Weather,weather);
        values.put(MyDatabaseHelper.Date,date);
        values.put(MyDatabaseHelper.Status, status);
        Cursor cursor = database.rawQuery("SELECT MAX(ID) FROM "+ MyDatabaseHelper.TABLE_INFO, null);
        database.insert(MyDatabaseHelper.TABLE_INFO, null, values);
        return cursor.getLong(0);

    }

LogCat

android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1
            at android.database.AbstractCursor.checkPosition(AbstractCursor.java:460)
            at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:136)
            at android.database.AbstractWindowedCursor.getLong(AbstractWindowedCursor.java:74)
            at com.example.project.project.API.InfoAPI.insertTimeSheet(InfoAPI.java:42)

I have posted a question regarding to Foreign Key.

Getting NULL value in foreign key column

Community
  • 1
  • 1
John
  • 684
  • 11
  • 35

2 Answers2

1

A CursorIndexOutOfBoundsException means that the Cursor by which you are trying to obtain or write data is not currently positioned at a valid result row. Note in particular that the Cursor obtained from rawQuery() is initially positioned just before the first row. This is sensible in part because it's the only place the Cursor can be positioned in the event that the query returns zero rows.

You would ordinarily use the cursor's positioning methods to move it to the row you want to access. For processing all rows in order, that would typically be moveToNext(). There is also moveToFirst(), moveToLast(), moveToPrevious(), moveToPosition(), and move().

John Bollinger
  • 160,171
  • 8
  • 81
  • 157
0
public long insertTimeSheet(String name,String weather,String date,String status){
  database=dbHelper.getWritableDatabase();
  ContentValues values=new ContentValues();
  values.put(MyDatabaseHelper.Name,name);
  values.put(MyDatabaseHelper.Weather,weather);
  values.put(MyDatabaseHelper.Date,date);
  values.put(MyDatabaseHelper.Status, status);
  database.insert(MyDatabaseHelper.TABLE_INFO, null, values);
  Cursor cursor = database.rawQuery("SELECT MAX(ID) FROM "+ MyDatabaseHelper.TABLE_INFO, null);
  if(cursor.getCount()>0){
    cursor.moveToFirst();
    return cursor.getLong(0);
  }

  return 0;
}
Deepak Goyal
  • 4,747
  • 2
  • 21
  • 46