Reputation: 47
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 =]
Upvotes: 0
Views: 1778
Reputation: 14408
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.
Upvotes: 0
Reputation: 5662
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
Upvotes: 0