SQLite db cursor crash - android

I am using a sqlite DB to store my users location while they are online, but for some reason I am getting this crash report and I don't know what it is or how to fix it.
android.database.CursorWindowAllocationException: Cursor window allocation of 2048 kb failed.
at android.database.CursorWindow.<init>(CursorWindow.java:108)
at android.database.AbstractWindowedCursor.clearOrCreateWindow(AbstractWindowedCursor.java:198)
at android.database.sqlite.SQLiteCursor.fillWindow(SQLiteCursor.java:138)
at android.database.sqlite.SQLiteCursor.getCount(SQLiteCursor.java:132)
at com.tech.databases.Routes_DB.savedGPSHasEntries(Routes_DB.java:109)
at com.tech.activity.Menu_dashboard.onLocationChanged(Menu_dashboard.java:2602)
at com.google.android.gms.c.b.r.a(Unknown:-1)
at com.google.android.gms.common.api.internal.h.b(Unknown:-1)
at com.google.android.gms.common.api.internal.h$c.handleMessage(Unknown:-1)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6314)
at java.lang.reflect.Method.invoke(Method.java:-2)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:872)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:762)
Every thing I have looked up says that it is caused by not closing my cursor, but on my code I close it every single time:
public boolean savedGPSHasEntries(){
boolean hasEntry = false;
String countQuery = "SELECT * FROM " + TABLE_SAVED_ROUTE;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int cnt = cursor.getCount();
if (cnt > 0)
hasEntry = true;
// Log.e("Database", "Count: " + cnt);
cursor.close();
return hasEntry;
}
And this is how I query the data:
if (routesDB.savedGPSHasEntries()) {
Log.e(TAG, "DB isn't empty");
}
So I am confused about this error or how to even begin to find out how to fix it.

CursorWindowAllocationException
This exception is thrown when a CursorWindow couldn't be allocated,
most probably due to memory not being available.
You should use
String countQuery = "SELECT count(*) FROM " + TABLE_SAVED_ROUTE;
Make sure, Close your DB also .
DEMO
cursor.close();
db.close();
Try with
String countQuery = "SELECT count(*) FROM " + TABLE_SAVED_ROUTE;
Cursor cursor = db.rawQuery(countQuery, null);
cursor.moveToFirst();
int count = cursor.getInt(0);
if(count>0)
{
}
For more info, See How to get row count in sqlite using Android?

Related

How to get last record from table SQLite

I have problem with receiving last data from table in Android SQLite.
Adding values works great but I struggle with receiving last date from table, here is code:
int getKoniec() {
SQLiteDatabase db = this.getReadableDatabase();
String sortOrder = TABELA_koniec + " DESC LIMIT 1";
Cursor cursor = db.query(
TABELA,
new String[] { "koniec" },
null,
null,
null,
null,
sortOrder
);
if(cursor != null) {
cursor.moveToFirst();
}
int koniecINT = cursor.getInt(0);
Log.v("VALUE: ","" + koniecINT);
cursor.close();
return koniecINT;
}
While adding values 10,9,8,7.. output (return koniecINT) is always 10.
Can you help me to solve this problem? Thanks
Try this query
select * from table_name order by row_id desc limit 1
or
mCursor.moveToLast();

Error in accessing data from cursor in SQLite

I am working on a SQLite program and getting an error saying
2019-07-14 21:07:37.465 13538-13538/? E/CursorWindow: Failed to read row 0, column -1 from a CursorWindow which has 1 rows, 2 columns.
2019-07-14 21:07:37.466 13538-13538/? D/AndroidRuntime: Shutting down VM
2019-07-14 21:07:37.467 13538-13538/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.xyz.sqlitelist, PID: 13538
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.xyz.sqlitelist/com.example.xyz.sqlitelist.MainActivity}: java.lang.IllegalStateException:
Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
.
.
Caused by: java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
W/ActivityManager: Force finishing activity com.example.xyz.sqlitelist/.MainActivity
String databaseToString(){
StringBuilder dbString= new StringBuilder();
SQLiteDatabase db = getWritableDatabase();
String query=" SELECT * FROM " + TABLE_PRODUCTS + " WHERE 1";
Cursor c=db.rawQuery(query,null);
c.moveToFirst();
while (!c.isAfterLast()){
if(c.getString(c.getColumnIndex("productname")) != null) {
c.moveToNext();
dbString.append(c.getString(c.getColumnIndex("productname")));
dbString.append("\n");
}
c.close();
db.close();
return dbString.toString();
}
Your column's name is "_productname" and not "productname" and this problem can be solved by not hardcoding this name since you have it in the variable COLUMN_PRODUCTNAME.
Also your code will miss rows because you use incorrectly moveToFirst(), moveToNext() and isAfterLast() when you only need moveToNext():
String databaseToString() {
StringBuilder dbString = new StringBuilder();
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM " + TABLE_PRODUCTS + " WHERE 1";
Cursor c = db.rawQuery(query, null);
int index = c.getColumnIndex(COLUMN_PRODUCTNAME);
while (c.moveToNext()) {
dbString.append(c.getString(index)).append("\n");
}
c.close();
db.close();
return dbString.toString();
}
Also that WHERE 1 in the sql statement is not needed unless you want to change it later to something meaningful.
you can change your code
String sql = " SELECT * FROM " + TABLE_PRODUCTS + " WHERE 1";
Cursor c = getWritableDatabase().rawQuery(sql, null);
while (c.moveToNext()) {
if(c.getString(c.getColumnIndex("productname")) != null)
{
dbString.append(c.getString(c.getColumnIndex("productname")));
dbString.append("\n");
}
}
c.close();
db.close();
return dbString.toString();

Android Studio SQLite database. unknown error

I am getting an error with the method below.
I would like to do a SELECT WHERE statement.
My goal is to know, if the variable name is already in my database.
The error seems to occur at statement.execute(); It is :-
"Caused By : unknown error (code 0): Queries can be performed using SQLiteDatabase query or rawQuery methods only. "
The program has worked properly many times before but now it does not.
The method is :-
public int count(String name) {
SQLiteDatabase database = getWritableDatabase();
String countQuery = "SELECT * FROM myBD WHERE NAME1 = ?";
SQLiteStatement statement = database.compileStatement(countQuery);
statement.clearBindings();
statement.bindString(1, name);
statement.execute();
//database.close();
SQLiteDatabase db = this.getReadableDatabase();enter code here
Cursor cursor = db.rawQuery(countQuery, null);
int count = cursor.getCount();
cursor.close();
database.close();
return count;
}
You could use the query convenience method e.g. :-
public int count(String name) {
SQLiteDatabase database = getWritableDatabase();
String whereclause = "NAME1=?";
String[] whereargs = new String[]{name};
Cursor cursor = database.query("myBD",null,whereclause,whereargs,null,null,null);
int count = cursor.getCount();
cursor.close();
database.close();
return count;
}
Note the above is in-principle code, it hasn't been checked or run and may therefore contain some errors.
Unknown errors are often related to subsequent lines following a ; the convenience methods enclose arguments and build the SQL on your behalf.
You can also use
database.rawQuery("Your query here");

Sqlite cursor.getCount() crashing app when ran

This code seems to crash my app every time it runs but data is stored in the data base and can be extracted anyone know why?
public int getContactsCount() {
String countQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
}
Dude! You closed your cursor!
Once you do cursor.close(), all the resources for cursor are released so you are trying to getCount on something that is not there.

Android cursor always returning null

I keep getting the following error
android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1
I know I have data in the database because a similar query for all the data (rather than a single entry) pulls out a list successfully
Here is my code for the database helper
public class DatabaseHandler extends SQLiteOpenHelper {
...
public Service getMostRecentService() {
SQLiteDatabase db = this.getReadableDatabase();
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS + " ORDER BY " + KEY_ID + " DESC LIMIT 1;";
Cursor cursor = db.rawQuery(selectQuery, null);
Service service = new Service();
if(cursor != null) {
service = new Service(cursor.getString(1), cursor.getString(2));
}
return service;
}
}
Any ideas why I keep getting the out of bounds exception?
You have not positioned your Cursor on a row. Initially, it is at position -1. Presumably, given your existing code, you should call moveToFirst() on the Cursor after the null check and before your getString() calls.

Categories

Resources