I have a very basic situation:
I have a table with around 5k rows:
CREATE TABLE "words" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL , "name" TEXT NOT NULL , "def" TEXT NOT NULL, "rand" INTEGER)
Which I periodically update using "UPDATE words SET rand=random()"
In android, when I create a cursor using rawQuery() using the following:
SELECT w.id, w.name, w.def, w.rand FROM words w ORDER BY w.rand ASC;
The returned cursor does not iterate in the correct order. E.g. it will output columns with rand values in the following order:
-1298882092
-2138143484
-1115732861
118839193
...
Does anyone know whats going on here? Shouldn't this work? If I run the exact same query in SQLiteManager it returns the results in the correct order, so this seems to be android/cursor specific.
UPDATE:
Here is the code in android, I have tried multiple ways:
Attempt 1:
Cursor cursor = db.rawQuery("SELECT w.id, w.name, w.def, w.rand FROM words w ORDER BY w.rand ASC", new String[]{});
Attempt 2:
Cursor cursor = db.query("words", new String[]{"id", "name", "def", "rand"},
null, null, null, null, "rand ASC");
In both cases I iterate like the following:
while(cursor.moveToNext()) {
...
Log.i("Test", cursor.getInt(3));
...
}
I solved it, was a simple oversight. The random() function returns a value which can be larger than a java int data type. This was producing overflow. Switched to getLong() and everything works fine. The cursor was iterating correctly all along.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With