我是 android-studio 的新手,正在尝试学习这个 + kotlin。 我尝试执行一个简单的 count(*) 请求,但计数始终返回 0。 我尽了一切努力。我无法找到会出现什么错误,我想我应该补充一些我不知道的东西。
class DatabaseHelper(context: Context) : SQLiteAssetHelper(context, DATABASE_NAME, null, DATABASE_VERSION) {
companion object {
private const val DATABASE_NAME = "lvl_database"
private const val DATABASE_VERSION = 1
}
}
class SubLevel : AppCompatActivity() {
private lateinit var dbHelper: DatabaseHelper
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_sublevel)
dbHelper = DatabaseHelper(this)
val db: SQLiteDatabase = dbHelper.writableDatabase
// Utilisation de try-catch pour gérer les éventuelles exceptions
try {
val cursor: Cursor = db.rawQuery("SELECT COUNT(*) FROM Levels", null)
val textView: TextView = findViewById(R.id.Sublevel_title)
if (cursor.moveToFirst()) {
val count = cursor.getInt(0)
textView.text = "Nombre total de lignes dans la table Levels : $count"
Log.d("DatabaseDebug", "Count from Levels: $count")
} else {
textView.text = "Aucune donnée dans la table Levels"
Log.d("DatabaseDebug", "Cursor is empty or failed to move to first.")
}
cursor.close()
} catch (e: Exception) {
Log.e("DatabaseError", "Error accessing database: ${e.localizedMessage}")
} finally {
db.close()
}
}
}
你的代码没有任何问题。
:-
<TextView
android:id="@+id/Sublevel_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView" />
:-
然后运行应用程序会导致:-
和日志包括:-
2024-05-07 14:11:27.489 I/SQLiteAssetHelper: successfully opened database lvl_database
2024-05-07 14:11:27.491 D/DatabaseDebug: Count from Levels: 3
因此,您的问题很可能与已复制到 assets/databases 文件夹中的文件有关。您可能应该将文件的副本重做到资产文件夹中,确保您已保存它并且它已将行插入到级别表中。
需要检查的一件事是,没有与源数据库文件同名但以 -wal 和 -shm 后缀的文件,就好像这些附加文件存在一样,这可能意味着数据库没有正确关闭,如果-wal文件不为空,说明有未提交的数据。