---
# System prepended metadata

title: DataStore 存取資料
tags: [Android, DataStore, kotlin]

---

# DataStore 存取資料

* 以往在存取一些簡易資料集，會使用SharedPreferences，但這個API有些缺陷，而DataStore就是取代它的
* 另外一個就是ProtoDataStore，但使用上還需設定一些schema，較為麻煩
* 下表為特點比較
![](https://i.imgur.com/J1Dn30i.png)

### 使用方法
* gradle 
```kotlin=
// Preferences DataStore
    implementation "androidx.datastore:datastore-preferences:1.0.0-rc01"

    // Coroutines
    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.0'
    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.4.3'

    // Coroutine Lifecycle Scopes
    implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.1"
    implementation "androidx.lifecycle:lifecycle-runtime-ktx:2.3.1"
```
* 簡易UI
![](https://i.imgur.com/P58vstw.png)

* Activity
    * dataStore讀寫都需要key，類型有幾種列在下表，這邊使用string
    * 上面的比較表顯示dataStore並沒有類型安全，所以在進行讀寫，必須清楚返回類型，不然會導致系統崩潰
    * 這也是dataStore比較適合用在簡單的數據集，如果用到較複雜類型的資料，還是建議使用資料庫
```kotlin=
class MainActivity : AppCompatActivity() {

    private var _binding: ActivityMainBinding? = null
    private val binding get() = _binding!!
    //這邊定義檔案名稱
    private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "settings")

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        _binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        binding.btnSave.setOnClickListener {
            lifecycleScope.launch {
                save(
                    binding.etSaveKey.text.toString(),
                    binding.etSaveValue.text.toString()
                )
            }
        }

        binding.btnRead.setOnClickListener {
            lifecycleScope.launch {
                val value = reda(binding.etReadkey.text.toString())
                binding.tvReadValue.text = value ?: "No valye found"
            }
        }
    }
    //寫入方式採用map 鍵值對作寫入
    private suspend fun save(key: String, value: String) {
        val dataStoreKey = stringPreferencesKey(key)
        dataStore.edit { settings ->
            settings[dataStoreKey] = value
        }
    }
    //讀取方式查詢key返回value
    private suspend fun reda(key: String): String? {
        val dataStoreKey = stringPreferencesKey(key)
        val preferences = dataStore.data.first()
        return preferences[dataStoreKey]
    }


    override fun onDestroy() {
        super.onDestroy()
        _binding = null
    }
}
```
![](https://i.imgur.com/zwzMqDg.png)

參考資料
[Philipp Lackner's channel](https://www.youtube.com/watch?v=McnVx7l5awk)


###### tags: `DataStore` `kotlin` `Android`