0

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

2
  • Are there any items in your database to retrieve? Commented Jun 18, 2013 at 15:01
  • You are right. No items in the DB. I've solved it but got another problem. Thanks Commented Jun 18, 2013 at 15:18

1 Answer 1

2

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;
Sign up to request clarification or add additional context in comments.

2 Comments

@ÐinaYŏŜri where is the NPE?
I found the solution, I was querying items that are not inserted yet. However, I have another problem if you may help me. I'm getting always the first record from the database with the AppName I've specified. but the database contains more than one record with the same AppName. How can I get them all? thanks for your help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.