Чтение данных из SQLCipher без создания класса DBHelper; Ошибка: не удалось открыть базу данных
Я создаю два приложения с одинаковым именем пакета:
- В первом приложении я использую SQLiteCipher, используя «Pass_Phrase» (БД Version_1) для операций CRUD, используя
Java
. - Во втором приложении я просто хотел прочитать данные (без создания класса DBHelper) из SQLiteCipher и поместить их в комнату (БД версии_2) во время миграции с использованием
Kotlin
.
Примечание. Изменения будут затронуты при обновлении приложения.
Я завершил первое приложение и застрял наsqliteCipherDataList()
во втором приложении. Нужна ваша помощь. Большое спасибо!
Код: UserDB.kt
@Database(entities = [User::class], version = 2, exportSchema = false)
abstract class UserDB : RoomDatabase() {
abstract fun userDAO(): UserDAO
companion object {
private var instance: UserDB? = null
private val MIGRATION_1_2: Migration = object : Migration(1, 2) {
override fun migrate(database: SupportSQLiteDatabase) {
val db = SQLiteDatabase.openOrCreateDatabase("User.db", passphrase, null)
db.rawExecSQL("ATTACH DATABASE '${encryptedDbPath}' AS encrypted KEY '${passphrase}'")
db.rawExecSQL("SELECT sqlcipher_export('encrypted')")
db.rawExecSQL("DETACH DATABASE encrypted")
db.close()
val version = database.version
Log.v("Old version", version.toString() + "")
}
}
// return userList
fun sqliteCipherDataList(): List<User> {
val userList: MutableList<User> = ArrayList()
val db = SQLiteDatabase.openDatabase(encryptedDbPath, passphrase, null, SQLiteDatabase.OPEN_READONLY)
val cursor: Cursor = db.query("Contacts", null, null, null, null, null, null)
if (cursor.moveToFirst()) {
do {
@SuppressLint("Range")
val emails = User(cursor.getString(cursor.getColumnIndex("Email")))
userList.add(emails)
} while (cursor.moveToNext())
}
cursor.close()
db.close()
return userList
}
fun getDatabase(context: Context): UserDB? {
if (instance == null) {
synchronized(this) {
Log.d("UserDB", "Creating Database")
instance = Room.databaseBuilder(
context.applicationContext,
UserDB::class.java, "RoomDB"
)
.addMigrations(MIGRATION_1_2)
.allowMainThreadQueries()
.build()
}
}
return instance!!
}
}
}
Код: MainAcitvity.kt
class MainActivity : AppCompatActivity() {
private var userDB: UserDB? = null
private var userList: List<User>? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
SQLiteDatabase.loadLibs(this)
val roomTextView = findViewById<TextView>(R.id.roomText)
userList = UserDB.sqliteCipherDataList()
Log.d("SQLiteCipherData", userList.toString())
userDB = UserDB.getDatabase(this)
userDB?.userDAO()!!.insertProductListToRoom(userList)
val u: User = userDB?.userDAO()!!.getProductFromRoom()[0]
Log.v("RoomDBData", u.Email)
roomTextView.text = u.Email
}
}
Исключение:
2022-07-22 16:24:21.085 18889-18889/com.example.sqlitecipherjava E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.sqlitecipherjava, PID: 18889
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.sqlitecipherjava/com.example.sqlitecipherjava.MainActivity}: net.sqlcipher.database.SQLiteDiskIOException: error code 10: Could not open database
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.SQLiteDiskIOException: error code 10: Could not open database
at net.sqlcipher.database.SQLiteDatabase.dbopen(Native Method)
at net.sqlcipher.database.SQLiteDatabase.openDatabaseInternal(SQLiteDatabase.java:2412)
at net.sqlcipher.database.SQLiteDatabase.openDatabase(SQLiteDatabase.java:1149)
at net.sqlcipher.database.SQLiteDatabase.openDatabase(SQLiteDatabase.java:1116)
at net.sqlcipher.database.SQLiteDatabase.openDatabase(SQLiteDatabase.java:1065)
at net.sqlcipher.database.SQLiteDatabase.openDatabase(SQLiteDatabase.java:1019)
at com.example.sqlitecipherjava.UserDB$Companion.sqliteCipherDataList(UserDB.kt:41)
at com.example.sqlitecipherjava.MainActivity.onCreate(MainActivity.kt:22)
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)