Javatpoint Logo
Javatpoint Logo

kotlin android sharedpreferences

Android Shared Preferences allow the activities or applications to store and retrieve data in the form of key and value. The data stored in the application remains to persist even if the app is closed until it has deleted or cleared.

The Android setting files use Shared Preferences to store the app setting data in the form of XML file under data/data/{application package}/share_prefs directory.

To access the Shared Preferences in our application, we need to get the instance of it using any of the following methods.

  • getPreferences()
  • getSharedPreferences()
  • getDefaultSharedPreferences()

Here preferences_fileName is the Shared Preferences file name and mode is the operational mode of the file.

The modifications over the preferences data are performed through the SharedPreferences.Editor object.

To delete the preferences data of application we call the method:

  • editor.remove("key"): it removes the specified key's value
  • editor.clear(): it removes all preferences data

The data stored in Shared preferences will lose when we perform any of the following operation:

  • Uninstalling the application.
  • Clearing the application data through setting.

Kotlin Android SharedPreferences Example

In this example, we will get the input data (id and name) from EditText and store them in a preference file. This preference data is retrieved and displayed in TextView by performing the click action on Button and make clear (remove) the preferences data.

activity_main.xml

Add the following code in the activity_main.xml layout file:

MainActivity.kt

Add the following code in the MainActivty.kt class file. In this class, we store the shared preferences data in the form of key-value in kotlinsharedpreference.

Output:

kotlin android sharedpreferences kotlin android sharedpreferences
kotlin android sharedpreferences

Using SharedPreferences, we can create the log-in and log-out functionality in our application by storing the state (data) of a user in the preferences file.


Next Topic#





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA