First of all, correct me if I'm wrong, but if you close a database connection, you can't use the Cursor you got from it, correct?
db.open();
Cursor c = db.query(true, "MyTable", columns, null, null, null, null, null, null);
db.close();
// The Cursor is empty now because the db was closed...
c.moveToNext();
Log.v(TAG, c.toString(0));
So is it there any way to use the Cursor after closing the database? Like is there any way to pass it elsewhere and use it kinda like an object? Or do you always have to leave the database connection open until you are done with the cursor?
I used
cursor.moveToLast()
, and it allowed me to use the cursor for iteration after database closure. I have no idea if this is intentional.However, it seems that the intended use of the open helper framework, is to open the db on activity start, and close it when the Activity is destroyed.
In an AsyncTask from within onCreate()...
The AsyncTask Thread.sleep() below is just to give enough time to show the dialog so that you can see it work. Obviously take that out when you're done playing. ;)
in onDestroy()... openHelper.close();
Otherwise, you will not be able to use android SimpleCursorAdapter, or anything like that. Of course the andriod docs are very lacking in this regard. But, remember, getWriteableDatabase() always returns the same cached reference, every single time, unless you closed it. So, if you go closing that reference willy-nilly, background threads and what not, that are using the same database, WILL die.
No, As it says in the link below, if you close the database, the cursor becomes invalid.
Will cursor be still alive after database is closed?
Correct.
I don't think so. I always closed the database when I'm done with the Cursor, even if I pass the cursor to another Cursor object.
Create method that will
return cursorobject;
and use the method wherever you need it. (Also create method that will close db after you are done)Otherwise the cursor will screw up.