Shared preference android kotlin fragment

Android SharedPreferences using Kotlin

Android SharedPreferences using Kotlin

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

In this tutorial, we’ll learn how to implement SharedPreferences in our Android Application using Kotlin.

What is Android SharedPreferences?

SharedPreferences is part of the Android API since API level 1. It’s an interface that allows us to store/modify/delete data locally. Generally, it is used to cache user local data such as login forms. The data is stored in the form of a key-value pair. You can create multiple files to hold the SharedPreferences data.

SharedPreferences Methods

  • getSharedPreferences(String, int) method is used to retrieve an instance of the SharedPreferences . Here String is the name of the SharedPreferences file and int is the Context passed.
  • The SharedPreferences.Editor() is used to edit values in the SharedPreferences .
  • We can call commit() or apply() to save the values in the SharedPreferences file. The commit() saves the values immediately whereas apply() saves the values asynchronously.

SharedPreferences Setting/Retrieving Values using Kotlin

We can set values on our SharedPreference instance using Kotlin in the following way.

val sharedPreference = getSharedPreferences("PREFERENCE_NAME",Context.MODE_PRIVATE) var editor = sharedPreference.edit() editor.putString("username","Anupam") editor.putLong("l",100L) editor.commit() 
sharedPreference.getString("username","defaultName") sharedPreference.getLong("l",1L) 

android shared preference types

The permitted types on a SharedPreference instance are:

Kotlin Code to Clear and Remove SharedPreferences Records

We can also clear all the values or remove a particular value by calling clear() and remove(String key) methods.

editor.clear() editor.remove("username") 

Note: Changes made to the editor after the commit or apply aren’t considered. The above way to save and retrieve values from a SharedPreference is nearly the same as we do in Java. So where’s the magic of Kotlin? That’s what we’ll see next through an example android application.

Android SharedPreferences Kotlin Project Structure

android shared preference kotlin project

In this application, we’ll have a login screen, which allows us to save/clear the form data.

Читайте также:  Does my browser support javascript

1. Layout code

The code for the activity_main.xml layout file is given below.

2. MainActivity Kotlin Code

The code for the MainActivity.kt Kotlin class is given below.

package com.journaldev.androidlysharedpreferences import android.content.Context import android.content.SharedPreferences import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.preference.PreferenceManager import android.view.View import com.journaldev.androidlysharedpreferences.PreferenceHelper.defaultPreference import com.journaldev.androidlysharedpreferences.PreferenceHelper.password import com.journaldev.androidlysharedpreferences.PreferenceHelper.userId import com.journaldev.androidlysharedpreferences.PreferenceHelper.clearValues import com.journaldev.androidlysharedpreferences.PreferenceHelper.customPreference import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity(), View.OnClickListener < val CUSTOM_PREF_NAME = "User_data" override fun onCreate(savedInstanceState: Bundle?) < super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) btnSave.setOnClickListener(this) btnClear.setOnClickListener(this) btnShow.setOnClickListener(this) btnShowDefault.setOnClickListener(this) >override fun onClick(v: View?) < val prefs = customPreference(this, CUSTOM_PREF_NAME) when (v?.id) < R.id.btnSave -> < prefs.password = inPassword.text.toString() prefs.userId = inUserId.text.toString().toInt() >R.id.btnClear -> < prefs.clearValues >R.id.btnShow -> < inUserId.setText(prefs.userId.toString()) inPassword.setText(prefs.password) >R.id.btnShowDefault -> < val defaultPrefs = defaultPreference(this) inUserId.setText(defaultPrefs.userId.toString()) inPassword.setText(defaultPrefs.password) >> > > object PreferenceHelper < val USER_ID = "USER_ID" val USER_PASSWORD = "PASSWORD" fun defaultPreference(context: Context): SharedPreferences = PreferenceManager.getDefaultSharedPreferences(context) fun customPreference(context: Context, name: String): SharedPreferences = context.getSharedPreferences(name, Context.MODE_PRIVATE) inline fun SharedPreferences.editMe(operation: (SharedPreferences.Editor) ->Unit) < val editMe = edit() operation(editMe) editMe.apply() >var SharedPreferences.userId get() = getInt(USER_ID, 0) set(value) < editMe < it.putInt(USER_ID, value) >> var SharedPreferences.password get() = getString(USER_PASSWORD, "") set(value) < editMe < it.putString(USER_PASSWORD, value) >> var SharedPreferences.clearValues get() = < >set(value) < editMe < it.clear() >> > 

Thanks to Kotlin Android Extensions, we don’t have to use findViewById for each XML view. In the above code, we are creating a singleton class using the object keyword. We are declaring an inline higher-order function named editMe(), which holds the logic for the edit operation. We’ve created separate properties for each of the values. We are using the get and set Kotlin properties to retrieve and set the data in the shared preferences. Kotlin has reduced the code verbosity and it looks much cleaner. Furthermore, we can make it more concise by using another Kotlin higher-order function shown below.

fun SharedPreferences.Editor.put(pair: Pair) < val key = pair.first val value = pair.second when(value) < is String ->putString(key, value) is Int -> putInt(key, value) is Boolean -> putBoolean(key, value) is Long -> putLong(key, value) is Float -> putFloat(key, value) else -> error("Only primitive types can be stored in SharedPreferences") > 

And we do the following while setting the values:

var SharedPreferences.password get() = getString(USER_PASSWORD, "") set(value) < editMe < it.put(USER_PASSWORD to value) >> 

This is as close as Kotlin can get you to the English Language. The output of the above application in action is given below.

Читайте также:  Parse cookie string python

You can download the source code from the following link: AndroidlySharedPreferences

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Источник

Shared Preferences With Kotlin

In this tutorial , we are going to learn how to use SharedPreferences In our Android Application to Store data in the form of value-key pairs with a simple Kotlin class.

Here w are going to learn how to create a simple custom SharedPreferences.kt class that can be used to every Android application if needed.

Overview

In many cases, we have to use SharedPreferences in our Application such as to store login status, save user-specific data and save application settings.

SharedPreferences is Application specific, so data stored in SharedPreferences can be lost in the following situations

  • By Uninstalling the Application
  • By Clearing application data (Using device settings)

Storing Data with SharedPreferences

Let’s start with the custom SharedPreference.kt class. Create a Kotlin class And Initialise SharedPreferences as shown below.

package com.kotlincodes.sharedpreferenceswithkotlin import android.content.Context import android.content.SharedPreferences /** * Created by Kolincodes on 10/05/2018. */ class SharedPreference(val context: Context)

PREF_NAME is the name of preference file.

Storing Data

To store String, Int and Boolean data we have three methods with the same name and different parameters (Method overloading). Add these methods to your SharedPreference.kt class.

To Store String data

fun save(KEY_NAME: String, value: Int)

To Store Int data

fun save(KEY_NAME: String, value: Int)

To Store Boolean data

fun save(KEY_NAME: String, status: Boolean)

Retrieve Data

To Retrieve the data stored in SharedPreferences use the following methods.

To Retrieve String

fun getValueString(KEY_NAME: String): String?

To Retrieve Int

fun getValueInt(KEY_NAME: String): Int

To Retrieve Boolien

fun getValueString(KEY_NAME: String): String?

Remove and Clear

To clear the entire SharedPreferences use the below code

fun clearSharedPreference() < val editor: SharedPreferences.Editor = sharedPref.edit() //sharedPref = PreferenceManager.getDefaultSharedPreferences(context); editor.clear() editor.commit() >

To remove a specific data

fun removeValue(KEY_NAME: String)

Now we are almost done with all the methods inside our SharedPreference.kt class.
Please find the Complete code for SharedPreference.kt file below.

Читайте также:  Casting primitive types java

SharedPreference.kt

package com.kotlincodes.sharedpreferenceswithkotlin import android.content.Context import android.content.SharedPreferences /** * Created by Kolincodes on 10/05/2018. */ class SharedPreference(val context: Context) < private val PREFS_NAME = "kotlincodes" val sharedPref: SharedPreferences = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) fun save(KEY_NAME: String, text: String) < val editor: SharedPreferences.Editor = sharedPref.edit() editor.putString(KEY_NAME, text) editor. commit() >fun save(KEY_NAME: String, value: Int) < val editor: SharedPreferences.Editor = sharedPref.edit() editor.putInt(KEY_NAME, value) editor.commit() >fun save(KEY_NAME: String, status: Boolean) < val editor: SharedPreferences.Editor = sharedPref.edit() editor.putBoolean(KEY_NAME, status!!) editor.commit() >fun getValueString(KEY_NAME: String): String? < return sharedPref.getString(KEY_NAME, null) >fun getValueInt(KEY_NAME: String): Int < return sharedPref.getInt(KEY_NAME, 0) >fun getValueBoolien(KEY_NAME: String, defaultValue: Boolean): Boolean < return sharedPref.getBoolean(KEY_NAME, defaultValue) >fun clearSharedPreference() < val editor: SharedPreferences.Editor = sharedPref.edit() //sharedPref = PreferenceManager.getDefaultSharedPreferences(context); editor.clear() editor.commit() >fun removeValue(KEY_NAME: String) < val editor: SharedPreferences.Editor = sharedPref.edit() editor.remove(KEY_NAME) editor.commit() >>

Implement in our Application

N ow we are going to implement our SharedPreference.kt class in a Simple Android Application.

The Image below Shows the Final output of the project

Setup Layout

The Layout for our MainActivity.kt class is shown below.

Setup MainActivity

Our Application have only one page with two EditText and Three Button.

First we Initialize our SharedPreferece.kt class in our MainActivity by

val sharedPreference:SharedPreference=SharedPreference(this)

On Save button click We stores EditText values into SharedPreferences.

On Retrieve Button click we Retrieve the saved data from SharedPreferences and set this data as the EditText hint.

On Clear button click we clear all the data from shared preferences.

Our MainActivity.kt class is given below.

package com.kotlincodes.sharedpreferenceswithkotlin import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.widget.Button import android.widget.EditText import android.widget.Toast class MainActivity : AppCompatActivity() < lateinit var edtName:EditText lateinit var edtEmail:EditText lateinit var btnSave:Button lateinit var btnRetrive:Button lateinit var btnClear:Button override fun onCreate(savedInstanceState: Bundle?) < super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val sharedPreference:SharedPreference=SharedPreference(this) edtName=findViewById(R.id.edt_name) edtEmail=findViewById(R.id.edt_email) btnClear=findViewById(R.id.btn_clear) btnSave=findViewById(R.id.btn_save) btnRetrive=findViewById(R.id.btn_retriev) btnSave.setOnClickListener < val name=edtName.editableText.toString() val email=edtEmail.editableText.toString() sharedPreference.save("name",name) sharedPreference.save("email",email) Toast.makeText(this@MainActivity,"Data Stored",Toast.LENGTH_SHORT).show() //to save an Int // sharedPreference.save("intval",1) //to save boolien // sharedPreference.save("bool",true) >btnRetrive.setOnClickListener < if (sharedPreference.getValueString("name")!=null) < edtName.hint = sharedPreference.getValueString("name")!! Toast.makeText(this@MainActivity,"Data Retrieved",Toast.LENGTH_SHORT).show() >else < edtName.hint="NO value found" >if (sharedPreference.getValueString("email")!=null) < edtEmail.hint = sharedPreference.getValueString("email")!! >else < edtEmail.hint="No value found" >> btnClear.setOnClickListener < sharedPreference.clearSharedPreference() Toast.makeText(this@MainActivity,"Data Cleared",Toast.LENGTH_SHORT).show() >> >

That’s it! Now run the project!

The full source code is available here.

Contribute to kotlincodes/Shared-Preference-With-Kotlin development by creating an account on GitHub.

Источник

Оцените статью