android sqlite cursor crashes the app - android

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 =]

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.

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

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.

Related

Why cursorObject.moveToFirst() is required on updating my database table value

I had a problem with updating of a column's value at a particular row. I had written
Cursor c = mDb.rawQuery("UPDATE "+book+" SET footnotes='" + note + "' WHERE chapter="+chapter+" and verse="+verse+"", null);
c.close();
But on adding c.moveToFirst() it worked. Why is that?
Cursor c = mDb.rawQuery("UPDATE "+book+" SET footnotes='" + note + "' WHERE chapter="+chapter+" and verse="+verse+"", null);
c.moveToFirst();
c.close();
Why is c.moveToFirst() necessary here, any particular reason?
There is an explation for c.moveToFirst()
(What is The use of moveToFirst () in SQLite Cursors) which briefly suggests that using c.moveToFirst() does two things
allows you to test whether the query returned an empty set
moves the cursor to the first result
But how does the above two things help in updation?
Think of rawQuery() as a wrapper for the C library sqlite3_prepare_v2() that compiles the SQL but does not run it, while think of moveTo..() as a wrapper for sqlite3_step() that is required for actually executing the prepared statement.
Related: What is the correct way to do inserts/updates/deletes in Android SQLiteDatabase using a query string?

Selecting int values using a cursor query

I am new to Android, and having some basic problems. One of them is the use of queries.
I store a boolean value as either 1 or 0 in the table (INTEGER field). However, when I select either on 1 or 0 using the query below I get no results. What am I doing wrong?
Cursor cursor = _db.query(_objectName, _fields.keySet().toArray(new String[0]), "parentId=? AND published=?", new String[] {String.valueOf(menuItem), String.valueOf(1)}, null, null, "level");
There is nothing wrong with your query. The problem must be elsewhere. Check your code and table structure. Maybe you are not sending the right values for parentId and published columns or the data in the table is not in the format you expected.
Use raw query
"Select * from "+TABLE_NAME+" where published = '"+String.valueOf(1)+"'";
You can put your integer value insted of 1

How to get 5 last record in the sqlite db in android?

Since the db does not have create date and some ordering field (but in my observation the last row is the latest record),
so how can i get the five last record in some condition e.g.
five record that their schoolid == 1?
Thanks
public Cursor select()
{
String orderBy = FIELD_pubKey+" DESC";
Cursor cursor = iReadDatabase.query(TABLE_NAME, null, null, null, null, null, orderBy);
cursor.moveToFirst();
return cursor;
}
There's no such thing as a last record or a first or a 42nd.
Which records appears last in the result of a query is dependent on the query plan, or an Explicit order by if you add one.
Select * From Table Where ...
The rows will be returned in whatever order the engine considers suitable at the time.
If you need them in specific order, then add an order by clause to the query, anything else is asking for it.
Something like
Select * From Table Order by SomeColumn desc limit 5
will do what you require.
Now what column you need to order by I've no idea, but you need one that will do the job, assuming automatic primary key, but note it is possible to mess with that.

Searching within cursors?

In android cursors I want to search within that cursor . i already have my query result in a cursor "c" and want to further search on the same cursor "c" with a like query .Any help would be appreciated
I have 2 cursors say
c1=fetchalldata();
c2=fetchwithcriteria(criteria);
c2 returns a coloumn id ID say at position say P2
I basically want the position of ID in cursor C1 without changing the order of records in c1.
What is your exact problem or query that you want to perform? Instead of going for searching inside a cursor, you should try to write the query that combines your exact query in one cursor itself. So, better would be write a single query with INNER JOIN or fetching Data from Multiple Tables or whatever is your query requirement. Cursor itself is an result/output of a query, so it won't be possible to write a query on a result.
solved Had to use a loop!!
int getPosition(int id){
c.moveToLast();
for(int i=c.getCount();i>0;i--,c.moveToPrevious())
{
if(id==c.getInt(c.getColumnIndexOrThrow(Databaseadapter.KEY_ROWID)))
{
return c.getPosition();
}
}
return 0;
}

How to go through every record in SQLite db?

I think it's kinda easy one but still I'm new to android programming so please have patience. I want to know how can I get the number of records (rows) in a specific table in my db. I need this so I can create a loop to go through every record and add each one of it to the specific Array and display it later on. This is the source:
db.openDataBase(); // open connection with db
Cursor c = db.getTitle(5); // loop here through db, right now I'm fetching only one record
startManagingCursor(c);
//adding areas to the list here
Area o1 = new Area();
o1.setOrderName(c.getString(1) + c.getString(2));
m_areas.add(o1);
db.close();
Does anyone can help me with this please? Thx in advance!
SELECT COUNT(*) FROM tablename
To get the number of rows in the cursor, use getCount.
To get the amount of total rows in a table, either use reinierposts solution, or do a select which select all rows in the table and get the count from the cursor. I'm guessing his solution is quicker though unless you actually need all the rows in the table.
Such a query would be:
SELECT * FROM footable;
You don't really need to get a count of how many first; instead, create a db.getTitles() function that returns all of the rows and returns a Cursor, then loop over the Cursor. Right now you probably have a query that looks something like SELECT ColumnA, ColumnB FROM Titles WHERE id = 5; just copy the function, remove the parameter and take off the WHERE clause so it looks like just SELECT ColumnA, ColumnB FROM Titles.
Then your code would look something like this:
db.openDataBase(); // open connection with db
Cursor c = db.getTitles();
startManagingCursor(c);
//adding areas to the list here
if (c != null && c.moveToFirst()) {
do {
Area o1 = new Area();
o1.setOrderName(c.getString(1) + c.getString(2));
m_areas.add(o1);
} while (c.next());
}
db.close();
We check if the function returned a cursor at all, then move to the beginning of the cursor and start looping, going to the next item each time through. For more information on the Cursor interface see the API here, or to learn more about database access and related design practices better in general I suggest going through the Notepad tutorial.

Categories

Resources