Skip to main content

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.

Comments

Popular posts from this blog

Flutter How to Start Android Activity from Flutter View

Flutter and Dart is an excellent combination for creating the UI, but for accessing the platform-specific service we need to open platform-specific activity. So lets in this article we will explore how to start an android activity and access the service from Flutter View. Create a Project for this Android Activity Flutter View Demo Create a Project From File menu select the New Flutter Project Enter the project name Select the AndroidX support and click on next After the above, we step click on Finish We will have the following project structure created. Create the Second Activity in Android Just go to the android folder and open it in separate windows. We will have the following project structure. Create the Activity Just right-click on the Kotlin folder and create a blank activity from the menu. If you create the activity then you may be required to upgrade the Gradle and do some import. So Just click on update and wait for the project s

Kotlin Parcelable Array Objects Send To Activity

We know that IPC (Inter Process Communication) between the activity is an extremely important part of any application development. We often required that we need to send some data to other activity. For example, we may be required to send an array of data, data could be an Integer, String, Long, Double, Float or any other custom data objects. So, In this example, we are going to learn how to implement the Kotlin Parcelable Array object to send the data from one activity to second activity. What is Parcel? The parcel class is designed as a high-performance IPC transport. A Parcel can contain both flattened data that will be unflattened on the other side of the IPC, and references to live IBinde r objects that will result in the other side receiving a proxy IBinder connected with the original IBinder in the Parcel. Create Kotlin Parcelable Array Objects Parcelable is API for placing the arbitrary objects into the Parcel. In Actual in android app development, Parcelable is an interface

Scan and List All Available WiFi Network In Android

In this tutorial, we learn how to connect to a WiFi hotspot in android by code. In this Demo we will create an as small app which will scan the all available network or Hotspot and list down the network when you select specific network, the application will connect that particular network. You May Like Below Topic: How to Read and Write JSON data using GSON WP Android App using REST and volley WP Android App using REST and volley part2 Implementation of SwipeRefreshLayout in RecyclerView Create Amazing Bottom Navigation Bar Without Any External Library Introduction In this tutorial, we learn how to connect to a WiFi hotspot in android by code. In this Demo we will create an as small app which will scan the all available network or Hotspot and list down the network when you select specific network, the application will connect that particular network. We will add this functionality to our existing Demo app " Video Gallery ". If you would like to check out t