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 Theme Creation, Programmatic Way

Flutter and Dart is an excellent combination for creating the mobile app with material design with nice GUI. Its lots of widget which help the developer for creating the app UI very fast with respect to the other language. You may face some problem in starting due to comm, curly brace and semicolon but after some time you will find the way how to work with these all stuff and it becomes very easy for you. But in this article, we are not going to discuss all these. In this article, we will handle a very interesting topic on how to create a custom theme or multiple themes and let's user decide which theme to use.



Create a flutter project



So let's create a flutter project by selecting the appropriate option from the File menu in android studio or Visual Code. If you are new to Flutter and Dart you can check out our recent post to get started Creating Cross-platform app using flutter.



Once your project is created you will get the default counter app and you try running the app in the…

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 sync completed.
Update the project build config …

Flutter State Management With Provider and ChangeNotifier

Flutter state management with provider library and why it's so important? There are lots of topics in flutter which are very important but out of those state management of your flutter application is the most important and little bit complicated as well. So in this article, I will try to explain how to use the provider package for managing the state of flutter and dart application and how to access the data down the hierarchy of the widget tree without recreating the whole UI.



Basic knowledge of the state management and data flow in the Flutter



Before starting the coding I would like to explain some basics about the Flutter application so that you can understand, why it's important to manage the state of your application in the correct way.



In Flutter, everything is a widget and whenever the state of your application changes the UI is recreated the UI with the new data. Let's list out the topic or problem that we are going to explore about state management.



Challenge of St…