android-how to close cursor in a class like this - android

I have this function inside my dbhelper class :
public Cursor getRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
Cursor c = db.query(DATABASE_TABLE, ALL_KEYS, where, null, null, null,null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
when I come to the activity where this class calls, I get this error (Please notice when I enter this activity I get this error not when leaving the activity ):
Finalizing a Cursor that has not been deactivated or closed. database......
Application did not close the cursor or database object that was opened here
it's a very long error .
someone told me to use c.close(); above return c, something like this:
public Cursor getRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
Cursor c = db.query(DATABASE_TABLE, ALL_KEYS, where, null, null, null,null, null);
if (c != null) {
c.moveToFirst();
}
c.close();
return c;
}
I tried it but now I get this error :
Access closed cursor
What should I do ? How should I close the cursor in this class?

You should close the Cursor in your Activity. like
Cursor c=getRow(rowID_Value);
c.close();
After getting used of your DB you must close this Cursor.

Close the cursor after using getRow function,i.e.
public Cursor getRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
Cursor c = db.query(DATABASE_TABLE, ALL_KEYS, where, null, null, null,null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
and use it like this
Cursor c1 = getRow(rowId);
//use cursor
//....
if(c1 != null)c1.close();
Note : rowId is the value of row which you want from database in long format.
Edit
Create Cursor c1; in your activity class.
check first if cursor is not null,then close it.
if(c1 != null)c1.close();
then get cursor as
c1 = getRow(rowId);
And onStop/onDestroy close cursor as
if(c1 != null)c1.close();

hello i have face this same problem i have solve this problem like
when i am query and returning ArrayList or JSON object not cursor
may you need to change your query
public JSONObject getRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
Cursor c = db.query(DATABASE_TABLE, ALL_KEYS, where, null, null, null,null, null);
if (c!= null & c.moveToFirst()) {
JSONObject jsonObj = new JSONObject();
jsonObj.put("key_Name", c.getString(c.getColumnIndex("your_column_name")));
// do for your all column and return this jsonObj and before returning close cursor
}
c.close();
return jsonObj;
}
this is for only returning one record for retuning set of record i am use this lib
https://github.com/commonsguy/cwac-loaderex
it will manage cursor operation itself and return us sqliteCursorLoader

Related

how to use where clause in cursor query in sqlite

I want only particular rows that has "E" inside the column "TX_IDT". I used the following code but apps stops. In logcat the error says it is at db.query line.
public Cursor getAllRows( ) {
String where = null;
SQLiteDatabase db = helper.getReadableDatabase();
String[] columns = { VivzHelper.UID, helper.UID,helper.NAME,helper.TX_IDT};
String whereClause = "TX_IDT = ? ";
String[] whereArgs = new String[] { "E" };
Cursor c = db.query( VivzHelper.TABLE_NAME, columns,whereClause,whereArgs, null, null, NAME + " ASC"); // for out btn
if (c != null) {
c.moveToFirst();
}
return c;
}
`
Seems like you want record's containing "E" ,
Try this
Cursor c = db.query(VivzHelper.TABLE_NAME, columns, helper.TX_IDT +" LIKE '%E%' ", null, null, null, null);

SQLite in Android: when I pass any name that contains a quote, it throws and error

Adapter.java
public String getID(String i) throws SQLException
{
db=DBHelper.getReadableDatabase();
String ij="No Track Found";
Cursor mCursor =
db.query(true, TABLE, new String[] {KEY_ID}, KEY_NAME + "=" + "'"+i+"'", null,
null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
if (mCursor.moveToFirst())
{
ij=mCursor.getString(0);
}
return ij ;
}
The Question is when I pass any song's name that contain "'"(e.g. alexander's blade) , it throws and error. Otherwise all fine.
You should use the selectionArgs parameter:
db.query(true, //distinct
TABLE, //table
new String[] {KEY_ID}, //columns
KEY_NAME + "=?", //selection
new String[] {i}, //selectionArgs
null, //groupBy
null, //having
null, //orderBy
null //limit
);
Using selectionArgs also help to prevent SQL Injection
You need to call your method like this:
Cursor c = bd.query(Constantes.TABELA_APLICATIVO, COLS, "urlandroid = ?", new String[]{url}, null, null, null);
The caracter "?" represents the values on Third parameter(String[]).

sqlite selection error

I got this code in one of my methods. It should check if the string is already in the database and if it is the db entry gets updated. If it is not there I catch the exception and just create the entry.
String s="hallo";
try {
Cursor c1 = dba.fetchSubject(s);
dba.updateSubject(c1.getLong(c1.getColumnIndex(DbAdapter.KEY_ROWID)), s, t, r);
} catch (SQLException e){
dba.createSubject(s, t, r);
}
The problem is fetchSubject allway throws an Exception.
I use a similar method to get a db entry by a rowId instead of a String, which is working:
public Cursor fetchSubject(long rowId) throws SQLException {
Cursor mCursor = database.query(true, DATABASE_TABLE2, new String[] {
KEY_ROWID, KEY_SUBJECT, KEY_TEACHER, KEY_ROOM}, KEY_ROWID
+ "=" + rowId, null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
The method called on top:
public Cursor fetchSubject(String subject) throws SQLException {
Cursor mCursor = database.query(true, DATABASE_TABLE2, new String[] {
KEY_ROWID, KEY_SUBJECT, KEY_TEACHER, KEY_ROOM}, KEY_SUBJECT
+ "=" + subject, null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
The error:
sqlite returned: error code = 1, msg = no such column: hallo
I don't know where my error is. Isn't it possible to use a string at the selection parameter?
Try adding single quotes around hallo
String s = "'hallo'";
Essentially what you're doing is telling your query: select blah blah blah from TABLE where subject = hallo. Since hallo isn't surrounded by quotes, it is trying to find a variable / column with that name. When we surround it with quotes, we are saying that we are looking for the string within these quotes, rather than a variable.
Think of it like normal programming..
String s = hallo;
is completely different than
String s = "hallo";

STRING in sqlite database query

When i try to search in row POINTA (text data type in SQLite) and I compare it to a String the program stops. This is the code:
public Cursor getpoints(String start,String end) throws SQLException {
Cursor mCursor = db.query(true, DATABASE_TABLE, new String[] {
KEY_PRIM,
NAME,
POINTA,
POINTA_LANG,
POINTA_LAT,
POINTB,
POINTB_LANG,
POINTB_LAT
},
POINTA +"=" +start,//here is the problem
null,
null,
null,
null,
null);
if (mCursor != null) {
mCursor.moveToFirst();
}
...
Same problem as this, you need single quotes around your start String, i.e.
POINTA + "='" + start + "'",

Check to see if a value exists in DB

I am trying to do a check if the User-name entered by the user exists in the DB.
public Cursor checkUsername(String username) throws SQLException {
Cursor mCursor = db.query(true, TABLE_USERS, new String[] { ID,
KEY_NAME, KEY_USERNAME}, KEY_USERNAME + "="
+ username, null, null, null, null, null);
if (mCursor != null) {
return true;
}
return false;
}
When i return true or false i am getting an Error saying
Type mismatch: cannot convert from boolean to Cursor
i just want to return true or false from the DBAdaptor back to the Activity.
Your function returns a Cursor
public Cursor checkUsername()
Either change it to return a boolean, or return a cursor.
Try reformatting your sql query and provide the 'where' clause as one of the parameters in the database call :
public Cursor getRoute(long rowIndex)
{
String where = KEY_ID + "=" + rowIndex;
return db.query(TBL_ROUTES, null, where, null, null, null, null);
}
Also, remember to close your cursor when you are finished with it, otherwise you will get other exceptions.

Categories

Resources