在SQLite DatabaseErrorHandler

时间:2016-11-03 06:34:32

标签: android sqlite error-handling database-restore

我一直致力于改进正在运行的 SQLite 数据库还原。更具体地说,当数据库损坏时(我已经在其中使用带有SQL的文件并将其复制到数据库文件而不是数据库的副本)。

我可以在没有处理程序的情况下使用SQL查看 sqlite_master ,(没有表检测到损坏)。

当我在研究技术时遇到DatabaseErrorHanlder时,我认为我会涉及 DatabaseErorHandler

我已经到了触发DataBaseErrorHandler的阶段(处理程序中的日志被调用(由于第二次尝试读取而两次))。然而,我报告的错误比我使用null而不是处理程序和应用程序崩溃(如果让处理程序关闭SQLite自动化,我相信,删除损坏的文件,因此任何调用处理程序重新创建它)。崩溃并不是一个问题,因为SQLite已经试图绕过腐败,但看起来处理程序会阻止它做它本来做的事情。)

在没有处理程序的情况下运行会导致以下消息(首先由应用程序编写为路标): -

11-03 16:36:13.414 10959-10959/? I/mjt.shopper: Thu Nov 03 16:36:13 AEDT 2016 Activity=dataBaseIntegrityCheck Method=MainDataHandling MSG=restore Database Integrity Check - IC Database created
11-03 16:36:13.415 10959-10959/? E/SQLiteLog: (26) file is encrypted or is not a database
11-03 16:36:13.416 10959-10959/? E/DefaultDatabaseErrorHandler: Corruption reported by sqlite on database: /data/data/mjt.shopper/databases/ICShopper
11-03 16:36:13.416 10959-10959/? E/DefaultDatabaseErrorHandler: deleting the database file: /data/data/mjt.shopper/databases/ICShopper

使用我得到的处理程序运行(处理程序发出相同的路标+路标): -

11-03 16:58:23.923 12265-12265/? I/mjt.shopper: Thu Nov 03 16:58:23 AEDT 2016 Activity=dataBaseIntegrityCheck Method=MainDataHandling MSG=restore Database Integrity Check - IC Database created
11-03 16:58:23.925 12265-12265/? E/SQLiteLog: (26) file is encrypted or is not a database
11-03 16:58:23.925 12265-12265/? I/mjt.shopper: Thu Nov 03 16:58:23 AEDT 2016 Activity=MainDataHandling Method=dataBaseIntegrityCheck MSG=DB onCorruption error handler invoked
11-03 16:58:23.925 12265-12265/? E/SQLiteLog: (26) file is encrypted or is not a database
11-03 16:58:23.927 12265-12265/? E/SQLiteDatabase: Failed to open database '/data/data/mjt.shopper/databases/ICShopper'.
                                                   android.database.sqlite.SQLiteDatabaseCorruptException: file is encrypted or is not a database (code 26): , while compiling: PRAGMA journal_mode
.............
11-03 16:58:23.928 12265-12265/? E/SQLiteOpenHelper: Couldn't open ICShopper for writing (will try read-only):
                                                     android.database.sqlite.SQLiteDatabaseCorruptException: file is encrypted or is not a database (code 26): , while compiling: PRAGMA journal_mode
'''''''''''''
11-03 16:58:23.929 12265-12265/? E/SQLiteLog: (26) statement aborts at 1: [PRAGMA user_version;] file is encrypted or is not a database
11-03 16:58:23.930 12265-12265/? I/mjt.shopper: Thu Nov 03 16:58:23 AEDT 2016 Activity=MainDataHandling Method=dataBaseIntegrityCheck MSG=DB onCorruption error handler invoked
11-03 16:58:23.934 12265-12265/? D/AndroidRuntime: Shutting down VM
11-03 16:58:23.934 12265-12265/? E/AndroidRuntime: FATAL EXCEPTION: main
                                                   Process: mjt.shopper, PID: 12265
                                                   android.database.sqlite.SQLiteDatabaseCorruptException: file is encrypted or is not a database (code 26)

DatabaseHelper代码是: -

public class IntegrityCheckDBHelper extends SQLiteOpenHelper implements DatabaseErrorHandler{

    public static final String DATABASE_NAME = "IC"+ShopperDBHelper.DATABASE_NAME;
    public static final int DATABASE_CORRUPTED = 1;
    private static int databasestate = 0;
    private Context context;

    public IntegrityCheckDBHelper(Context context,
                                  String name,
                                  SQLiteDatabase.CursorFactory factory,
                                  int version, DatabaseErrorHandler errorHandler) {
        super(context, DATABASE_NAME,factory,1,errorHandler);
        this.context = context;

    };

    public void onCreate(SQLiteDatabase db) {};
    public void onUpgrade(SQLiteDatabase db, int oldversion, int newversion) {};
    public void onCorruption(SQLiteDatabase db) {
    }
    public boolean checkDB() {
        SQLiteDatabase icdb = this.getReadableDatabase();
        String icsqlstr = " PRAGMA quick_check";
        Cursor iccsr;
        iccsr = icdb.rawQuery(icsqlstr,null);
        return false;
    }
    public static void setDatabaseCorrupted() {
        databasestate = DATABASE_CORRUPTED;
    }
    public boolean isDatabaseCouurpted() {
        if(databasestate != 0) return false;
        return true;
    }
}

请注意!此Helper专门用于检查还原文件是否为用户(因此onCreate / onUpgrade无需执行任何操作我认为)。

这里是相关代码,即 dataBaseIntegrityCheck 方法(即从正在恢复的备份中创建数据库文件,以检查备份是否创建了有效的数据库 ): -

private boolean dataBaseIntegrityCheck() {

        final String THIS_METHOD = "dataBaseIntegrityCheck";
        String sqlstr_mstr = "SELECT name FROM sqlite_master WHERE type = 'table' AND name!='android_metadata' ORDER by name;";
        Cursor iccsr;
        boolean rv = true;
        DatabaseErrorHandler myerrorhandler = new DatabaseErrorHandler() {
            @Override
            public void onCorruption(SQLiteDatabase sqLiteDatabase) {
                mjtUtils.logMsg(mjtUtils.LOG_INFORMATIONMSG,"DB onCorruption error handler invoked",THIS_ACTIVITY,THIS_METHOD,true);
                dbcorrupted = true;
            }
        };
        mjtUtils.logMsg(mjtUtils.LOG_INFORMATIONMSG,"Restore Databae Integrity Check - Starting",THIS_METHOD,THIS_ACTIVITY,true);
        try {
            FileInputStream bkp = new FileInputStream(backupfilename);
            OutputStream ic = new FileOutputStream(icdbfilename);
            while ((copylength = bkp.read(buffer)) > 0) {
                ic.write(buffer, 0, copylength);
            }
            ic.close();
            bkp.close();

            mjtUtils.logMsg(mjtUtils.LOG_INFORMATIONMSG,"restore Database Integrity Check - IC Database created",THIS_METHOD,THIS_ACTIVITY,true);

            //Note SQLite will actually check for corruption and if so delete the file
            IntegrityCheckDBHelper icdbh = new IntegrityCheckDBHelper(this,null,null,1,myerrorhandler);

            //>>>>>>>>>>>>> Errors all point here (the getReadableDatabase)
            SQLiteDatabase icdb = icdbh.getReadableDatabase();

            if(dbcorrupted) {
                mjtUtils.logMsg(mjtUtils.LOG_INFORMATIONMSG,"DB corrupted",THIS_ACTIVITY,THIS_METHOD,true);
                return false;
            }

            //Check to see if there are any tables, if wrong file type shouldn't be any
            iccsr = icdb.rawQuery(sqlstr_mstr,null);
            if(iccsr.getCount() < 1) {
                errlist.add("Integrity Check extract from sqlite_master returned nothing - Propsoed file is corrupt or not a database file.");
                rv = false;
            }
            iccsr.close();
            icdb.close();

        } catch (IOException e) {
            e.printStackTrace();
            errlist.add("Integrity Check Failed Error Message was " + e.getMessage());
        }

        if(!rv) {
            // AlertDialog removed.
        }
        return rv;
    }

要重新迭代,问题主要是关于DatabaseErrorHandler以及我能做什么,不能和/或应该做什么。

我找到的文档以及我看过的很多帖子似乎都没有用。

1 个答案:

答案 0 :(得分:2)

COLLATION 'UTF8_BIN' is not valid for CHARACTER SET 'latin1'中的相关代码如下所示:

SQLiteDatabase.open()

所以你的 try { openInner(); } catch (SQLiteDatabaseCorruptException ex) { onCorruption(); openInner(); } 处理程序必须在它返回之前恢复数据库;这不能推迟到晚些时候。

如果您实际上并不想恢复您尝试打开的数据库,那么使用onCorruption()处理程序是没有意义的。