Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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. Also the blog by Android developers doesn't have any information about it.

like image 513
oyeraghib Avatar asked Sep 02 '25 09:09

oyeraghib


2 Answers

As mentioned by @Shafaat and @DarShan there are two ways to clear data from 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
context.dataStore.edit { preferences ->
    preferences.remove(YOUR_TOKEN)
}
like image 130
oyeraghib Avatar answered Sep 05 '25 01:09

oyeraghib


You can clear your preferences using this way

requireContext().dataStore.edit {
it.remove(key)
}
like image 29
Shafaat Mursleen Avatar answered Sep 05 '25 01:09

Shafaat Mursleen