0

Hello Stackoverflow members!

There is a strange problem in my app. When there is a few db rows (more than 0) in the table, the query works good. when there is no rows in the table, the app crashes ,and then, if I remove these lines, the app works ok:

        Cursor result = db.rawQuery("Select * from users ORDER BY `ID` DESC" ,null);
    result.moveToFirst();
   String lastuser = result.getString(resultSet2.getColumnIndex("username"));

I hope you can help me =]

1
  • 1
    ALWAYS include the logcat in your question if you get exceptions. Jul 20, 2014 at 13:35

3 Answers 3

1

It looks like the crash is caused by the result not having any rows. You can check how many rows you obtained by using the getCount method on your cursor. If it's zero, do not try to get results from an empty set.

You can read more about cursors here.

0
0

After making your query, the cursor will be before the first position. So you have to move it to the first position, as you already do it with result.moveToFirst(). However, if your result was empty, the there is no first position and you get an Exception.

What you could do is either test

if(result.moveToFirst()){
       // here you can access the content
}

or you try it with a loop (that way you can also react on results with multiple rows)

while(result.moveToNext()){
      String lastuser = result.getString(resultSet2.getColumnIndex("username"));
      // here you can access ALL row entries one after another, or just the one row
}

Here is a clear tutorial on using SQLite – hope it helps

0

First change your query as(remove single quote from ID )

Cursor result = db.rawQuery("Select * from users ORDER BY ID DESC" ,null);

And as @Gooey suggest You can check how many rows you obtained by using the getCount.

So use

Cursor result = db.rawQuery("Select * from users ORDER BY ID DESC" ,null);

if ((result != null) && (result.getCount() > 0)) {
    result.moveToFirst();
    String lastuser = result.getString(resultSet2.getColumnIndex("username"));
}

And post logcat exception,if still problem occur.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.