简体   繁体   English

如何从 Android [Kotlin] 中的 DataStore Preferences 中清除数据

[英]How to clear the data from DataStore Preferences in Android [Kotlin]

I want to know how can I clear the data from Data Store Preferences in Android.我想知道如何从 Android 中的数据存储首选项中清除数据。 In my use-case when the user presses the Logout I want to clear the saved authentication code from the data store preferences.在我的用例中,当用户按下注销时,我想从数据存储首选项中清除保存的身份验证代码。

Upon searching I found there was a way to do it in Shared Preferences using edit() and clear() method, but I can't find any such methods in Data Store Preferences.搜索后,我发现有一种方法可以在 Shared Preferences 中使用edit()clear()方法,但我在 Data Store Preferences 中找不到任何此类方法。 Also the blog by Android developers doesn't have any information about it. Android 开发人员的博客也没有关于它的任何信息。

You can clear your preferences using this way您可以使用这种方式清除您的偏好

requireContext().dataStore.edit {
it.remove(key)
}

As mentioned by @Shafaat and @DarShan there are two ways to clear data from DataStore Preferences.正如@Shafaat 和@DarShan 提到的,有两种方法可以从DataStore Preferences 中清除数据。

  1. Clearing all the data in the data store preferences清除数据存储首选项中的所有数据
context.dataStore.edit { preferences ->
    preferences.clear()
}
  1. If you want to remove the specific token (value) from DataStore如果要从 DataStore 中删除特定令牌(值)
context.dataStore.edit { preferences ->
    preferences.remove(YOUR_TOKEN)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM