Шифрование существующей базы данных Room -> Исключение: файл не является базой данных: при компиляции: select count(*) from sqlite_master;

Я шифрую существующую базу данных Room. Когда я звонюinsert()способ вставки данных в комнату иfindAll()метод для извлечения данных из комнаты. После шифрования базы данных комнаты и запуска приложения возникает исключение как для методов, так и для сбоя приложения. Я много исследовал, но проблема не решена. Пожалуйста, помогите мне решить это исключение. И скажи мне, чего мне не хватает. Большое спасибо!

Код UserDB.kt:

      @Database(entities = [User::class], version = 1)
abstract class UserDB : RoomDatabase() {
    abstract fun userDao(): UserDAO

    companion object {
        @Volatile
        private var instance: UserDB? = null

        fun getInstance(context: Context, charArray: CharArray): UserDB? {
            if (instance == null) {
                synchronized(UserDB::class) {

                    val passphrase: ByteArray =
                        SQLiteDatabase.getBytes(charArray)

                    val factory = SupportFactory(passphrase)

                    instance = Room.databaseBuilder(
                        context.applicationContext,
                        UserDB::class.java,
                        "RoomDB"
                    ).openHelperFactory(factory).build()

                }
            }
            return instance
        }
    }
}

Код UserDAO.kt

      @Dao
interface UserDAO {
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun insert(user: User)

    @Query("SELECT * FROM User")
    fun findAll(): List<User>
}

Код MainActivity.kt:

      class MainActivity : AppCompatActivity() {
    private var userDB: UserDB? = null
    private var pass: String? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        pass = "!@#ABC"

        SQLiteDatabase.loadLibs(this)

        userDB = UserDB.getInstance(this, pass!!.toCharArray())

        userDB?.userDao()?.insert(User(0, "Ahmer"))

        val textView1 = findViewById<TextView>(R.id.textData)

        // TODO Display from Room
        val u: User = userDB?.userDao()!!.findAll()[0]
        Log.v("RoomProduct", u.id.toString() + " : " + u.name)
        textView1.text = StringBuilder("${u.id} : ${u.name}")
    }
}

Исключение:

      E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.roomwithcipher, PID: 32748
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.roomwithcipher/com.example.roomwithcipher.MainActivity}: net.sqlcipher.database.SQLiteException: file is not a database: , while compiling: select count(*) from sqlite_master;
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3114)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3257)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1948)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7050)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:965)
     Caused by: net.sqlcipher.database.SQLiteException: file is not a database: , while compiling: select count(*) from sqlite_master;
        at net.sqlcipher.database.SQLiteCompiledSql.native_compile(Native Method)
        at net.sqlcipher.database.SQLiteCompiledSql.compile(SQLiteCompiledSql.java:91)
        at net.sqlcipher.database.SQLiteCompiledSql.<init>(SQLiteCompiledSql.java:64)
        at net.sqlcipher.database.SQLiteProgram.<init>(SQLiteProgram.java:91)
        at net.sqlcipher.database.SQLiteQuery.<init>(SQLiteQuery.java:48)
        at net.sqlcipher.database.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:60)
        at net.sqlcipher.database.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:2016)
        at net.sqlcipher.database.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1902)
        at net.sqlcipher.database.SQLiteDatabase.keyDatabase(SQLiteDatabase.java:2673)
        at net.sqlcipher.database.SQLiteDatabase.openDatabaseInternal(SQLiteDatabase.java:2603)
        at net.sqlcipher.database.SQLiteDatabase.openDatabase(SQLiteDatabase.java:1247)
        at net.sqlcipher.database.SQLiteDatabase.openOrCreateDatabase(SQLiteDatabase.java:1322)
        at net.sqlcipher.database.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:166)
        at net.sqlcipher.database.SupportHelper.getWritableDatabase(SupportHelper.java:83)
        at androidx.room.RoomDatabase.inTransaction(RoomDatabase.java:622)
        at androidx.room.RoomDatabase.assertNotSuspendingTransaction(RoomDatabase.java:399)
        at com.example.roomwithcipher.UserDAO_Impl.insert(UserDAO_Impl.java:46)
        at com.example.roomwithcipher.MainActivity.onCreate(MainActivity.kt:23)
        at android.app.Activity.performCreate(Activity.java:7327)
        at android.app.Activity.performCreate(Activity.java:7318)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3094)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3257) 
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78) 
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) 
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1948) 
        at android.os.Handler.dispatchMessage(Handler.java:106) 
        at android.os.Looper.loop(Looper.java:214) 
        at android.app.ActivityThread.main(ActivityThread.java:7050) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:965) 
  • Я добавил следующие зависимости вbuild.gradle(:app)
          implementation 'net.zetetic:android-database-sqlcipher:4.3.0@aar'
    implementation "androidx.sqlite:sqlite:2.0.1"

    implementation 'androidx.room:room-runtime:2.3.0'
    annotationProcessor("androidx.room:room-compiler:2.3.0")
    kapt("androidx.room:room-compiler:2.3.0")

0 ответов

Другие вопросы по тегам