Android - Can SQLite Cursor's be used after closing the database? Android - Can SQLite Cursor's be used after closing the database? sqlite sqlite

Android - Can SQLite Cursor's be used after closing the database?


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?


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?

Correct.

So is it there any way to use the Cursor after closing the database?

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.

Like is there any way to pass it elsewhere and use it kinda like an 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)

Or do you always have to leave the database connection open until you are done with the cursor?

Otherwise the cursor will screw up.


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()...

new StartupTask().execute();

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. ;)

private class StartupTask extends AsyncTask{    private ProgressDialog progressDialog;    @Override    protected Object doInBackground(final Object... objects)    {        openHelperRef.getWritableDatabase();        try        {            Thread.sleep(5000);        }        catch (InterruptedException e)        {            e.printStackTrace();        }        return null;    }    @Override    protected void onPreExecute()    {        super.onPreExecute();        runOnUiThread(new Runnable()        {            public void run()            {                progressDialog = ProgressDialog.show(                    MyActivity.this, "Title",                    "Opening/Upgrading the database, please wait", true);            }        });    }    @Override    protected void onPostExecute(Object object)    {        super.onPostExecute(object);        progressDialog.dismiss();    }}

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.