之前嘗試了類似 iOS UserDefaults 的 SharedPreferences 來存取簡易的資料,
這次來嘗試用 SQLite 在手機上建立 Database.
我們建立一個 MemberDatabaseHelper 繼承於 SQLiteOpenHelper.
其中 SQLiteOpenHelper 後面的參數為,context, db name, CursorFactory , version
class MemberDatabaseHelper(context:Context): SQLiteOpenHelper(context, "example.db", null, 4){}
然後他有兩個方法
override fun onUpgrade(p0: SQLiteDatabase?, p1: Int, p2: Int) {}
override fun onCreate(db: SQLiteDatabase) {}
我們在 onCreate 的時候就檢查,如果名為 members 的 Table 不存在就去創建
override fun onCreate(db: SQLiteDatabase) {
val sql = "CREATE TABLE if not exists $tableName ( id integer PRIMARY KEY autoincrement, name text)"
db.execSQL(sql)
}
fun addName(name:String) {
val values = ContentValues()
values.put("name", name)
writableDatabase.insert(tableName, null, values)
}
fun getNames(): ArrayList<ItemModel> {
val cursor = readableDatabase.query(tableName, arrayOf("id", "name"), null, null, null, null, null)
val members = ArrayList<ItemModel>()
try {
if(cursor.moveToFirst()){
do {
val name = cursor.getString(cursor.getColumnIndex("name"))
val id = cursor.getInt(cursor.getColumnIndex("id"))
val item = ItemModel(id, name)
members.add(item)
} while(cursor.moveToNext())
}
} catch (e:Exception) {
} finally {
if(cursor != null && !cursor.isClosed){
cursor.close()
}
}
println("總共有 ${cursor.count} 筆資料")
return members
}