DataStore-Preferences DataStore
DataStore是用來解決數據存儲,內部使用了Coroutines和Flow,提供了兩種不同的實現。
1.Preferences DataStore
儲存key,value不需要定義架構,不提供Type safety。
2.Proto DataStore
儲存Model要定義Protocol Buffers,提供Type safety。
createDataStore("資料庫名稱"):創建資料庫
preferencesKey:資料的Key
DataStore.edit:寫入資料
DataStore.data:將資料取出利用Flow傳回
Flow<T>.collect:取得資料
導入
android {
kotlinOptions { jvmTarget = "1.8" }
}
dependencies {
implementation "androidx.datastore:datastore-preferences:1.0.0-alpha01"
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.9'
}
創建Model
data class User(var account: String?, var password: String?)
MainActivity
class MainActivity : AppCompatActivity() {
//共用同個key
object PreferencesKeys {
val ACCOUNT = preferencesKey<String>("account")
val PASSWORD = preferencesKey<String>("password")
}
//創建userInfo的資料庫
private val dataStore by lazy {
applicationContext.createDataStore(name = "userInfo")
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
CoroutineScope(Dispatchers.IO).launch {
val user = dataStore.data.map { user ->
val account = user[PreferencesKeys.ACCOUNT] ?: ""
val password = user[PreferencesKeys.PASSWORD] ?: ""
//把值塞入Model中回傳
User(account, password)
}
//從Model取出資料
withContext(Dispatchers.Main) {
user.collect { user ->
account.setText(user.account)
password.setText(user.password)
}
}
}
}
//儲存資料
fun save(view: View) {
CoroutineScope(Dispatchers.IO).launch {
dataStore.edit { user ->
user[PreferencesKeys.ACCOUNT] = account.text.toString()
user[PreferencesKeys.PASSWORD] = password.text.toString()
}
}
}
}
儲存資料後可來這邊查看
Device File Explorer > data > data > Package Name > files > datastore