简体   繁体   中英

Android sqlite helper error while getting data back

Hi all im using a sqlite helper class, but i have a little problem using a select statement. I want to get the id of a datebase item by its name.

I use this select method:

public Cursor selectShift (String name){
    SQLiteDatabase db = dbHandler.getReadableDatabase();
    Cursor c = db.query(TABLE_NAME, null, "name=" + name, null, null, null, null);
    c.moveToFirst();
    db.close();
    return c;
}

And when i call this i use this:

if(handler.selectShift(name)!=null){
      Cursor c = handler.selectShift(name);
      id = c.getInt(c.getColumnIndex("_id"));
      c.close();      
  }

And then is get this error:

android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0

As if its not exists, but i checked the name string is correct, and when i display the names in a listview i see that name, so it exists.

Can someone help me how to fix this?

1 - there shoudld be check is there any data in cursor or not......c.getCount>0 or c.moveToFirst() or c.isAfterLast().......

if(handler.selectShift(name)!=null){
      Cursor c = handler.selectShift(name);

if (c.moveToFirst()){ //<--------------
   do{  //<---------if you not need the loop you can remove that
       id = c.getInt(c.getColumnIndex("_id"));
   }while(cursor.moveToNext());
}



  c.close();      

}

2- not sure but looks in select query as ' <variable> ' are not there in where clause with variable

"SELECT COUNT(*) FROM " + tableName + " WHERE " + commentFieldName + " = '" + comment + "'"; 

or better to use parametrized statement

String query = "SELECT COUNT(*) FROM " + tableName + " WHERE columnName = ?";
cursor = db.rawQuery(query, new Sring[] {comment});

The issue appears to be here

"name="  <-It should be "name = "+name

Following should work

Cursor cursor= db.query(TABLE_IMAGES,null, "name" +" = ?", new String[]{name},  null, null, null);

Unless your name variable is already formatted (or not a TEXT) for sql I am guessing you need a little quotation. Maybe something like this

Cursor c = db.query(TABLE_NAME, null, "name= \'" + name + "\'", null, null, null, null);

Thanks for your help, i found the problem. It was in the cursor method, the solution is:

public Cursor selectShift (String name){
    SQLiteDatabase db = dbHandler.getReadableDatabase();
    Cursor c = db.query(TABLE_NAME, new String[] {"_id"}, "name LIKE '"+name+"%'", null, null, null, null);
    c.moveToFirst();
    db.close();
    return c;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM