Ðina YŏŜri
Ðina YŏŜri

Reputation: 55

Exception when retrieving values from SQLite database Android

I'm using SQLite in my Android Application. It consists of a table with 4 columns - first one is the "id" (integer) and the last one is AppName (String). When I try to retrieve the values from the database by giving specific id, it is done successfully. However, when I try to retrieve the values from the database by giving the AppName it does not work and gives me an exception.

The following is the code of the function that I use for the second case where I get an exception:

@Override
public NameVO getAppInfo(String appName) {
     SQLiteDatabase db = this.getReadableDatabase();
      Cursor cursor = db.query(TABLE_NAME, new String[] { KEY_ID,
              KEY_ENERGY, KEY_CPU, KEY_APPNAME }, KEY_APPNAME + "=?",
        new String[] {appName} , null, null, null, null);
      if (cursor != null)
       cursor.moveToFirst();
      NameVO nameVO = new NameVO(Integer.parseInt(cursor.getString(0)),
        cursor.getString(1), cursor.getString(2), cursor.getString(3));
      // return nameVO
      return nameVO;
}

The exception that I get is:

E/AndroidRuntime(14852): android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0

Do you have any idea how to have this working?

Thanks in advance

Upvotes: 0

Views: 270

Answers (1)

zozelfelfo
zozelfelfo

Reputation: 3776

You are probably getting an empty cursor. Try using this

if(cursor != null) {
 if(cursor.moveToFirst()) {
  NameVO nameVO = new NameVO(Integer.parseInt(cursor.getString(0)),
    cursor.getString(1), cursor.getString(2), cursor.getString(3));
  // return nameVO
  return nameVO;
 }
}
return null;

EDIT:

If you want to get all your NameVo try doing this

List<NameVO> name_list= new ArrayList<NameVO();
if(cursor != null) {
 if(cursor.moveToFirst()) {
  do {
        NameVO nameVO = new NameVO(Integer.parseInt(cursor.getString(0)),
          cursor.getString(1), cursor.getString(2), cursor.getString(3));
        name_list.add(nameVO);
     }
  while(cursor.moveToNext());

 }
 return name_list;
}
return null;

Upvotes: 2

Related Questions