iT邦幫忙

2018 iT 邦幫忙鐵人賽
DAY 22
0
Software Development

Kotlin 30 天,通過每天一個小 demo 學習 Android 開發系列 第 22

Kotlin 開發第 22 天 LocalDatabase (SQLite + SQLiteOpenHelper)

LocalDatabase
之前嘗試了類似 iOS UserDefaults 的 SharedPreferences 來存取簡易的資料,

這次來嘗試用 SQLite 在手機上建立 Database.

  • SQLite
  • SQLiteOpenHelper

SQLiteOpenHelper

我們建立一個 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)
    }

Write Data

    fun addName(name:String) {
        val values = ContentValues()
        values.put("name", name)
        writableDatabase.insert(tableName, null, values)
    }

Read Data

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

}

筆記

  • TODO: 更多 SQLite 的操作嘗試

參考


上一篇
Kotlin 開發第 21 天 LayoutSwitch (RecyclerView + GridLayoutManager + Out of memory)
下一篇
Kotlin 開發第 23天 GoogleVoice (RecognizerIntent)
系列文
Kotlin 30 天,通過每天一個小 demo 學習 Android 開發30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言