Couldn't read row 0, col 1 from CursorWindow - android

I'm trying to get the number of entries my DB holds - in the most simple way possible.
I'm trying to use the rawQuery "SELECT Count(*) FROM Students" and then from the cursor to do an getInt method to get the number and use it later on.
this is my method
public int getNumberOfEntries() {
SQLiteDatabase db = helper.getWritableDatabase();
String query = ShaqedDB.NUMBER_OF_ENTRIES;
Cursor d = db.rawQuery(query, null);
d.moveToFirst();
while (!d.isAfterLast()) {
int numberReturned = d.getInt(0);
d.moveToNext();
return numberReturned;
}
return 0;
}
I've looked everywhere - and I cannot find a solution to why am I keep getting the cursor error that the cursor cannot read row 0, col 1... even though I think I point it to col 0

if you don't need to write, you should use getReadableDatabase(); instead of getWritableDatabase();. In
d.getInt(0);
0 is the index of column you want to retrieve the value. Don't hardcode the value. Ask the cursor to retrieve the column index
d.getInt(d.getColumnIndexOrThrow("COLUMN_NAME"));
about your query, you want to now the number of results returned by your query. You can retrieve this value asking the cursor's count:
public int getNumberOfEntries() {
SQLiteDatabase db = helper.getReadableDatabase();
String query = ShaqedDB.NUMBER_OF_ENTRIES;
Cursor d = db.rawQuery(query, null);
return d.getCount();
}

Related

Cursor returning 0

I have a function where I want to get the sum of values on a MySQL database table's row. This is my code:
public int getSum(int var) {
int x=0;
// Select All Query
String selectQuery = "SELECT sum(amount) FROM donations WHERE aid = '"+aid+"'";
SQLiteDatabase db = openOrCreateDatabase("shareity", Context.MODE_PRIVATE, null);
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
x = cursor.getInt(0);
} while (cursor.moveToNext());
}
// return contact list
Log.d("id", "Id" + "," + x);
return x;
}
And I'm calling this in the onCreate() like this:
getSum(idk);
where idk is an integer. But my this returns 0. Can I know why please? The table's row I want to get the sum of, is also integer.
Finally figured it out. The problem was with the SQLite database. I had to use a php file to download the database from the mysql server to the local Sqlite server and then loop through it

Single value from cursor to int

I can't seem to figure out how I get the result from my select query (which should be one number) into my int min. Found different solution using Google but none worked.
I need the min value in order to check if the score that the current player has is higher than the lowest score in order to get in the highscores.
public int getMin(){
System.out.println("in getmin");
String selectQuery = "SELECT MIN(score) FROM tblscore;";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
int min = "something here to put the result in the int"
cursor.close();
db.close();
return min;
}
You could read the value through a cursor, but for single-valued queries like this, there is helper function in the DatabaseUtils class which makes things simpler:
public int getMin(){
String selectQuery = "SELECT MIN(score) FROM tblscore";
SQLiteDatabase db = this.getReadableDatabase();
try {
return (int)DatabaseUtils.longForQuery(db, selectQuery, null);
} finally {
db.close();
}
}
First you need to point the cursor to the first line:
cursor.moveToFirst();
Then you can use Cursor.getInt to get the value:
int min = cursor.getInt(0);

java.lang.IllegalStateException: Couldn't read row 0, col 10 from CursorWindow

Please check following code:
List<Database> zaznamy = new ArrayList<Database>();
String selectQuery = "SELECT X FROM Data WHERE LEVEL_1 =-24 AND LEVEL_2 =-48 AND LEVEL_3 =-55 AND LEVEL_4 =0";
File dbfile = new File("/sdcard/rtls/Databases/"+DBName );
SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(dbfile, null);
Cursor cursor = db.rawQuery(selectQuery,null);
String bodX="empty";
if (cursor.moveToFirst())
{
do {
Database zaznam = new Database();
zaznam.setX(Integer.parseInt(cursor.getString(10)));
zaznamy.add(zaznam);
} while (cursor.moveToNext());
for (Database cn : zaznamy)
{
Log.d("X: ", Integer.toString(cn.getX()));
bodX = (cn.getX()+ "//").toString();
Log.d("X", bodX);
}
}
It says it Couldn't read row 0, col 10 from CursorWindow. I´ve tested the database with SQLite browser. Database has exactly 1 X at column 10, row 0. SQL query is working correctly I believe. Can someone tell me, why it cant be read? Or where is mistake?
EDIT:
corrected the code to:
do {
Database zaznam = new Database();
zaznam.setX(cursor.getInt(10));
zaznamy.add(zaznam);
} while (cursor.moveToNext());
because of integer value of 10th column, but still no luck. Same error
Your query has only one column in projection - column 'X'. That column has index 0 in query projection so to make your code work change your loop to looks like this:
do {
Database zaznam = new Database();
zaznam.setX(cursor.getInt(0));
zaznamy.add(zaznam);
} while (cursor.moveToNext());
To avoid that kind of problems in the future use following:
cursor.getInt(cursor.getColumnIndexOrThrow("X");
Remember that column index is related to query projection and not the sequence of columns in your database, so for example when you write "select B A C from SOME_TABLE" column B will have index 0 and column A will have index 1 etc. even if in your database they are in alphabetical order A B C.
I was having the same issue. For me. A simple work around may be:
// query database and populate an ArrayList
private void getDataFromDatabase() {
Cursor cursor = dbConnector.getSomeData();
if (cursor.getCount() > 0) {
cursor.moveToFirst();
for(int i = 0; i < cursor.getCount(); i++) {
// get column data from database and add it to ArrayList
anArrayList.add(cursor.getString(cursor.getColumnIndexOrThrow("Attr")));
cursor.moveToNext();
} // end for
} // end if
dbConnector.close();
} // end getDataFromDatabase
WHERE "Attr" is the Attribute/column name you wish to query and the anArrayList is the ArrayList you want to store the data in.

Update table using rawQuery() method does not work

I tried the following SQLite query:
int idServizo = 150;
String whereClause = id_servizio+" = '"+idServizio+" ' ";
ContentValues cv = new ContentValues();
cv.put("sync", 1);
int r = dbManager.updateTable("myTable", cv, whereClause);
Where fields sync and id_servizio are both integer.
The method updateTable is:
public int updateTable(String table, ContentValues values, String whereClause){
int r = mDb.update(table, values, whereClause, null);
return r;
}
// mDb is SQLiteDatabase object
All this works good.
But if I try this with the rawQuery() method:
public Cursor RawQuery(String sqlQuery, String[] columns){
return mDb.rawQuery(sqlQuery, columns);
}
The table is not updated! even if no error occurs.
int idServizo = 150;
String updateQuery ="UPDATE myTable SET sync = 1 WHERE id_servizio = "+idServizio;
dbManager.RawQuery(updateQuery, null);
Why does this not work?
This is because when a rawQuery is executed cursor is returned. Without the call to cursor.moveToFirst() and cursor.close() the database won't get updated.
int idServizo = 150;
String updateQuery ="UPDATE myTable SET sync = 1 WHERE id_servizio = "+idServizio;
Cursor c= dbManager.rawQuery(updateQuery, null);
c.moveToFirst();
c.close();
I dont know the need to call moveToFirst() but this works fine and the database gets updated.
Problem solved.
http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html
Can't works because rawQuery runs the provided SQL and returns a Cursor over the result set.
If I want to return a table I have to use rawQuery, otherwise no!
Increase the value of a record in android/sqlite database
You should use db.execSQL() instead db.rawQuery().
Instead of doing this:
Cursor c= dbManager.RawQuery(updateQuery, null);
c.moveToFirst();
c.close();
You just need this:
dbManager.execSQL(updateQuery, null);
----------------------------------------------------------------------------
Posting answer because sometimes many people (like me) not reading comments.
Most popular answer is not correct but Yaqub Ahmad's comment is correct.
Answer from CommonsWare explained in this answer:
rawQuery() is for SQL statements that return a result set. Use
execSQL() for SQL statements, like INSERT, that do not return a result
set.
----------------------------------------------------------------------------
Documentation for execSQL:
public void execSQL (String sql)
Execute a single SQL statement that is NOT a SELECT or any other SQL statement that returns data.
Documentation for rawQuery:
public Cursor rawQuery (String sql,
String[] selectionArgs)
Runs the provided SQL and returns a Cursor over the result set.
Your update call formats the ID as string, while the rawQuery call formats is as number.
Assuming that the ID in the table indeed is a string, use:
String updateQuery = "UPDATE myTable SET sync = 1 WHERE id_servizio = '" + idServizio + "'";

Android and SQLite - retrieve max id of a table

I am trying to create a method to retrieve the max id of a specific table.
This is the code that doesn't work:
private long getMaxId()
{
String query = "SELECT MAX(id) AS max_id FROM mytable";
Cursor cursor = db.rawQuery(query, new String[] {"max_id"});
int id = 0;
if (cursor.moveToFirst())
{
do
{
id = cursor.getInt(0);
} while(cursor.moveToNext());
}
return id;
}
The exception being thrown is this:
E/AndroidRuntime(24624): android.database.sqlite.SQLiteException: bind or column index out of range: handle 0x200408
I suppose the problem is this line:
id = cursor.getInt(0);
Does anybody have an idea of how to fix this?
Thanks.
Try replacing:
Cursor cursor = db.rawQuery(query, new String[] {"max_id"});
with
Cursor cursor = db.rawQuery(query, null);
From the rawQuery description , for the 2nd argument:
You may include ?s in where clause in
the query, which will be replaced by
the values from selectionArgs. The
values will be bound as Strings.
Since you dont have any placeholders in your SQL query, maybe it is the source of the problem.

Categories

Resources