Saving Apps Data In Android Using SharedPreferences

Saving Apps Data In Android Using SharedPreferences

Saving Apps Data in Android App Development is the one of the very important and there are multiple ways to store the data on an android device. We can save the data using the following method.

  • SharedPreference
  • Save data into files
  • SQLite Database
  • Room Database

Depending on our requirement we choose which method is best suited for our apps. In this tutorial, we are going to take a look at SharedPreferences.

Saving Apps Data using SharedPreferences

First of all, we are going to explore the SharedPreferences. SharedPreferences is very useful where we want to store some key-value pair or we can say a small amount of data. Let’s assume a scenario where you want to check that whether the app is going to open the first time or previously its has open to the user.

If the user is opening the app for the first time then you want to store the name, email and mobile number of the user or if not then you just want to show these details under user profile section.

So this kind of data can be stored into the user device very easily using the SharedPreference.

So, let’s start creating the app by keeping this concept in the mind and code the app.

Type of Preferences

We have two option to create the preference to save the data to the Android device. If we need to use single preference then we can simply use the getPreferences() method as given below.

var singlePreference=this.getPreferences(Context.MODE_PRIVATE)

If we need to use the multiple preferences in your application and want to call from any method then we have to get the instance using getSharedPreferences() method as given below.

val sharedPreferences=this.getSharedPreferences("com.nplix.sharedPreference",
 Context.MODE_PRIVATE)

Here, in above example com.nplix.sharedPreference is the name of the preference so we can create multiple preferences by passing the name in the first parameter of the getSharedPreferences method.

Second parameter Context.MODE_PRIVATE indicate that this preference can be used by only this application, no other installed application can use the preferences.

How to save the data into SharedPreferences?

For saving the data into the preferences we need to edit the preferences like given below.

sharedPreferences.edit().putBoolean("firstTime", true).apply()

We can also use the commit() instead of apply() but apply is the recommended method as its save the data in background thread where commit save the data immediately.

In above code “firstTime” is the key and true is the value. We are using the putBoolean() method because we are storing the boolean value, if we have save the String then we can use the putString() method.

How to get the Saved Data from shared preferences?

For reading the data from the shared Preferences we have to use the get method for the particular type using the sharedPreferences.getBoolean(key,defVal) method.

Here, deVal is the default value that will be passed by the preference if the key does not exist in the persistence storage.

First, make the instance of your sahredPreferences using the below code.

val sharedPreferences=this.getSharedPreferences("com.nplix.sharedPreference", Context.MODE_PRIVATE)

Read boolean value using the code below.

var firstTime=sharedPreferences?.getBoolean("firstTime",false)

Read string value using code like below.

var name=sharedPreferences.getString("name",null)

Saving data using the sharedPreferences Editor

For saving the data to sharedPreferences we can also use the Editor and save the data at once.

var editor: SharedPreferences.Editor? =sharedPreferences.edit();
            editor?.putBoolean("firstTime",true)
            editor?.putString("name","Pawan Kumar")
            editor?.putString("email","pawan@nplix.com")
            editor?.apply()

Sample MainActivity file in Kotlin for SharedPreferences

Below is the sample code to show how to use the SharedPreferences. What was done by this code? Using this code we are saving the name, email into SharedPreferences when the user opens the app first time and then onward we show the details which were saved earlier.

package com.nplix.sharedpreferenceexample

import android.content.Context
import android.content.SharedPreferences
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.preference.Preference
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.TextView

class MainActivityKotlin : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main_java)
        //Mode_Private means only your app can use this preference not any other app
        var textView=findViewById<TextView>(R.id.textView)
        var clearBtn=findViewById<Button>(R.id.clear);

        val sharedPreferences=this.getSharedPreferences("com.nplix.sharedPreference", Context.MODE_PRIVATE)
        var firstTime=sharedPreferences?.getBoolean("firstTime",false)

        if(firstTime==false) {
            textView.text="User Open First Time, Details saved into Shared Preferences"
            var editor: SharedPreferences.Editor? =sharedPreferences.edit();
            editor?.putBoolean("firstTime",true)
            editor?.putString("name","Pawan Kumar")
            editor?.putString("email","pawan@nplix.com")
            editor?.apply()

          /*  sharedPreferences.edit().putBoolean("firstTime", true).apply()
            sharedPreferences.edit().putString("name", "Pawan Kumar").apply()
            sharedPreferences.edit().putString("email", "pawan@nplix.com").apply()*/

        }
        else{
            var stringBuilder:StringBuilder= StringBuilder("Stored Value\n")
            stringBuilder.append("Name"+sharedPreferences.getString("name",null)+"\n")
            stringBuilder.append("Email:"+sharedPreferences.getString("email",null))
            textView.text = stringBuilder.toString()

            Log.d("SharedPreference:", "Name:"+sharedPreferences.getString("name",null)
            +"Email:"+sharedPreferences.getString("email",null))
        }
        clearBtn.setOnClickListener(View.OnClickListener { sharedPreferences.edit().clear().apply()
        textView.text="All data are cleared"
        })




     ///   var singlePreference=this.getPreferences(Context.MODE_PRIVATE)
      //  singlePreference.edit().putString("test","Single Test Data").commit()
    }
}

If you want you can take these input from user using the Edit Box and save the same or any other activity depending on the requirement of the app.

Get Email Updates!

Signup now receive an email once I publish new content. I will never give away, trade or sell your email address. You can unsubscribe at any time.

Join 911 other subscribers

Leave a Reply

Close Menu