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

前端 未结 3 1805
广开言路
广开言路 2021-02-07 10:11

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.quer         


        
3条回答
  •  遥遥无期
    2021-02-07 10:46

    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.

提交回复
热议问题