How can I refresh/reopen an SQLite database after restoring it, when using a singleton for the database helper

让人想犯罪 __ 提交于 2019-12-24 07:32:47

问题


I have incorporated Database Backup and restore in my App. This all works fine except that when I restore the database, due to the use of a singleton DBHelper along with only closing the database when the App closes, the in-memory copy of the Database continues to be used after the restore.

Closing the App and re-starting uses the new database. However, rather than tell the user to do this. I would like to seamlessly access the restored database.

This is the code that detects and then reports upon a successful restore :-

                if(copytaken && origdeleted && restoredone) {
                    errlist.add("Database successfully restored." +
                            "\n\nYou should close the ShopWise App and then restart it.");
                    resulttitle = "Restore was successful.";
                    //DBHelper.reopen(context); <== implemented as below
                }
                ..... Displays dialog with text from above

This is the DBHelper (note expand method is used to create/amend the tables)

class DBHelper extends SQLiteOpenHelper {

    private static final String DBNAME = DBConstants.DATABASE_NAME;

    /**
     * Consrtuctor
     *
     * @param context activity context
     * @param name    database name
     * @param factory cursorfactory
     * @param version database version
     */
    DBHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
    }

    /**
     * Instantiates a new Db helper.
     *
     * @param context the context
     */
    DBHelper(Context context) {
        super(context, DBConstants.DATABASE_NAME, null, 1);
    }

    private static DBHelper instance;

    /**
     * Gets helper.
     *
     * @param context the context
     * @return the helper
     */
    static synchronized DBHelper getHelper(Context context) {
        if(instance == null) {
            instance = new DBHelper(context);
        }
        return instance;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        expand(db, false);
    }
    .......

Thinking that you should close the database an reopen it. I tried adding a reopen method in the DBHelper as follows:-

public static void reopen(Context context) {
        instance.close();
        instance = null;
        instance = new DBHelper(context);
    }

and then invoked this from within the code when the restore was OK (as per comment). However, this results in the following :-

java.lang.IllegalStateException: attempt to re-open an already-closed object: SQLiteDatabase:

02-16 16:41:20.938 2683-3050/mjt.shopwise E/SQLiteLog: (28) file unlinked while open: /data/data/mjt.shopwise/databases/ShopWise
02-16 16:41:25.171 2683-2683/mjt.shopwise D/AndroidRuntime: Shutting down VM
02-16 16:41:25.171 2683-2683/mjt.shopwise E/AndroidRuntime: FATAL EXCEPTION: main
                                                            Process: mjt.shopwise, PID: 2683
                                                            java.lang.RuntimeException: Unable to resume activity {mjt.shopwise/mjt.shopwise.MainActivity}: java.lang.IllegalStateException: attempt to re-open an already-closed object: SQLiteDatabase: /data/data/mjt.shopwise/databases/ShopWise
                                                                at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2986)
                                                                at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3017)
                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1347)
                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                at android.os.Looper.loop(Looper.java:135)
                                                                at android.app.ActivityThread.main(ActivityThread.java:5254)
                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                at java.lang.reflect.Method.invoke(Method.java:372)
                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
                                                             Caused by: java.lang.IllegalStateException: attempt to re-open an already-closed object: SQLiteDatabase: /data/data/mjt.shopwise/databases/ShopWise
                                                                at android.database.sqlite.SQLiteClosable.acquireReference(SQLiteClosable.java:55)
                                                                at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1312)
                                                                at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1255)
                                                                at mjt.shopwise.DBCommonMethods.getTableRows(DBCommonMethods.java:106)
                                                                at mjt.shopwise.DBCommonMethods.getTableRows(DBCommonMethods.java:59)
                                                                at mjt.shopwise.DBCommonMethods.getTableRowCount(DBCommonMethods.java:29)
                                                                at mjt.shopwise.DBCommonMethods.getTableRowCount(DBCommonMethods.java:43)
                                                                at mjt.shopwise.DBShopMethods.getShopCount(DBShopMethods.java:44)
                                                                at mjt.shopwise.MainActivity.getDBCounts(MainActivity.java:207)
                                                                at mjt.shopwise.MainActivity.onResume(MainActivity.java:163)
                                                                at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1257)
                                                                at android.app.Activity.performResume(Activity.java:6076)
                                                                at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2975)
                                                                at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3017) 
                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1347) 
                                                                at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                at android.os.Looper.loop(Looper.java:135) 
                                                                at android.app.ActivityThread.main(ActivityThread.java:5254) 
                                                                at java.lang.reflect.Method.invoke(Native Method) 
                                                                at java.lang.reflect.Method.invoke(Method.java:372) 
                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) 
                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 

回答1:


The trick is very simple, do not close the database just reset the DBHelper.

So the reopen method could be:-

public static void reopen(Context context) {
        instance = new DBHelper(context);
    }

Of course, you could also do away with the text telling the user to close and restart the App.

So the code that detects and reports on a successful restore could be:-

if(copytaken && origdeleted && restoredone) {
                    errlist.add("Database successfully restored.");
                    resulttitle = "Restore was successful.";
                    DBHelper.reopen(context); <== implemented as below
                }



回答2:


the reopen code that worked for me was:

public void reopen(Context context, String DbFilePath) {
        instance = new DBHelper(context, DbFilePath);
    }

the difference from the previous answer is the removal of the "static" from the function definition which required the instance to be static as well. this prevented the actual reopening of the database



来源:https://stackoverflow.com/questions/42266031/how-can-i-refresh-reopen-an-sqlite-database-after-restoring-it-when-using-a-sin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!