Contents

Android Shared Preferences is one of the way to store user and application data in device. It stores data as key/value pairs.

 

Step 1   -
Initialising Shared Preferences

Context context = YourActivityName.this;(getActivity()  //in fragment)
SharedPreferences pref = context.getSharedPreferences(
        "MyPrefs", Context.MODE_PRIVATE);
Here, MyPrefs is your shared preference name.

Preferences can be private or public.

1. MODE PRIVATE :  The default mode, where the created file can only 
    be accessed by the calling application.
2. MODE_WORLD_READABLE / MODE_WORLD_WRITABLE : Any
    application can read / update the preference data.
   
You can perform operations like store, read, update, delete, clear, 
check whether data contains or not (using key).The following data
types are supported by the SharedPreferences class:
   1 Boolean values.
   2 Float values.
   3 Integer values.
   4 Long values.
   5 String values.
   6 String set value.
   7 You can also store Object by converting it into string
     (using GSON).
 

Step 2   -
Storing Data

/* Need editor object to changes in data */
SharedPreferences.Editor editor= pref.edit(); 

/* to store Boolean values */
editor.putBoolean("Keyname", “your value”); 
Like: editor.putBoolean("flag", true);  

/* to store Float values */
editor.putFloat("Keyname", “your value”); 
Like: editor.putFloat("salary", 1.2f); // 

/* to store Integer values */
editor.putInt("Keyname", “your value”); 
Like: editor.putInt("number", 12);

/* to store Long values */
editor.putLong("Keyname", “your value”);
Like: editor.putLong("current_time", minToMillisec(NumberPicker2.getValue()));

/* to store String values */
editor.putString("Keyname", “your value”);
Like: editor.putString("username", "hacker.smart");

/* to store String set values */
editor.putStringSet("Keyname", “your value”);
Ex: HashSet<String> fruitSet = new HashSet<String>();
dataset.add("Mango");
dataset.add("Banana");
dataset.add("Cherry");
edit.putStringSet("fruits", fruitSet);

/* for apply changes 
editor.commit() -> writes its data to persistent storage immediately
editor.apply() -> will handle data in the background */
editor.commit(); or editor.apply();
 

Step 3   -
Reading Data

( while reading the data from shared preferences second parameter is optional, you can put value which is called default value, it means if there is no key then it will return default value )

/* to get Boolean value */
editor.getBoolean("Keyname", “default value”);
Like: editor.getBoolean("flag", false);

/* to get Float value */
editor.getFloat("Keyname", “default value”);
Like: editor.getFloat("salary", 0.0f);


/* to get Integer value */
editor.getInt("Keyname", “default value”);
Like: editor.getInt("number", 0);

/* to get Long value */
editor.getLong("Keyname", “default value”);
Like: editor.getLong("current_time", 0);

/* to get String value */
editor.getString("Keyname", “default value”);
Like: editor.getString("username", "");

/* to get String set values */
editor.getStringSet("Keyname", “default value”);
HashSet<String> fruitSet  = editor.getStringSet("fruits", null);
 

Step 4   -
Updating Data

( it will override the current data if exist )

/* Need editor object to changes in data */
SharedPreferences.Editor editor= pref.edit(); 

/* to store Boolean value */
editor.putBoolean("Keyname", “your value”); 
Like: editor.putBoolean("flag", false);

/* to store Float value */
editor.putFloat("Keyname", “your value”); 
Like: editor.putFloat("salary", 1.5f);

/* to store Integer value */
editor.putInt("Keyname", “your value”); 
Like: editor.putInt("number", 15);

/* to store Long value */
editor.putLong("Keyname", “your value”);
Like: editor.putLong("current_time", minToMillisec(NumberPicker2.getValue()));

/* to store String value */
editor.putString("Keyname", “your value”);
Like: editor.putString("username", "hacker.good");

/* to store String set values */
editor.putStringSet("Keyname", “your value”);
Ex: HashSet<String> fruitSet = new HashSet<String>();
dataset.add("Apricots");
dataset.add("Avocados");
dataset.add("Eggfruit");
edit.putStringSet("fruits", fruitSet);

/* for apply changes 
editor.commit() -> writes its data to persistent storage immediately
editor.apply() -> will handle data in the background */
editor.commit(); or editor.apply();


Deleting Data:-

/* to remove particular key */
pref.remove(“Keyname”);
Like: pref.remove("username");

/* for apply changes 
editor.commit() -> writes its data to persistent storage immediately
editor.apply() -> will handle data in the background */
editor.commit(); or editor.apply();
 

Step 5   -
Clear Data

/* to remove all keys */
pref.clear();

/* for apply changes 
editor.commit() -> writes its data to persistent storage immediately
editor.apply() -> will handle data in the background */
editor.commit(); or editor.apply();
 

Step 6   -
Check Data is available or not

( it will return true if key is available and return false if key is not available )

/* for check whether shared preference is available or not*/
pref.contains(“Keyname”);
Like: pref.contains("username");
 

Step 7   -
Store Object in Shared Preference

First of All, You need to add below dependency in your app gradle file for 
Convert object to string.

dependencies {
	implementation 'com.google.code.gson:gson:2.8.0'
}
 

Step 8   -
Storing data

Gson gson = new Gson();
ArrayList<String> fruits = new ArrayList<String>();
list.add("apple");
list.add("Banana");
list.add("Cherry");
String fruitsString = gson.toJson(fruits);
pref.putString("fruit_list", fruitsString);
pref.commit(); or pref.apply();
 

Step 9   -
Reading data

String json = pref.getString("fruit_list", null);
Type type = new TypeToken<ArrayList<String>>() {}.getType();
ArrayList<String> fruits =  gson.fromJson(json, type);
 

Step 10   -
Complete Demo of SharedPreference : Here is your AndroidManifest.xml file:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.shared.preferences">

   <application
       android:allowBackup="true"
       android:icon="@mipmap/ic_launcher"
       android:label="@string/app_name"
       android:roundIcon="@mipmap/ic_launcher_round"
       android:supportsRtl="true"
       android:theme="@style/AppTheme">
       <activity
           android:name=".MainActivity"
           android:screenOrientation="portrait">
           <intent-filter>
               <action android:name="android.intent.action.MAIN" />

               <category android:name="android.intent.category.LAUNCHER" />
           </intent-filter>
       </activity>
       <activity
           android:name=".SaveActivity"
           android:screenOrientation="portrait" />
       <activity
           android:name=".GetDataActivity"
           android:screenOrientation="portrait" />
   </application>
</manifest>


Add this dependencies to your app level module build.gradle (Module: app)

/*
* Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object.
* */
implementation 'com.google.code.gson:gson:2.7'
 

Step 11   -
Following data store to res/values/strings.xml.

<resources>
   <string name="app_name">Shared Preference</string>
   <string name="save_data">Save Data</string>
   <string name="get_data">Get data</string>
   <string name="delete_single_data">delete single data</string>
   <string name="clear">clear all data</string>
   <string name="user_name">User name</string>
   <string name="age">Age</string>
   <string name="hobbies">Hobbies</string>
   <string name="cricket">Cricket</string>
   <string name="football">Football</string>
   <string name="hockey">Hockey</string>
   <string name="save">Save</string>
</resources>
 

Step 12   -
Your activity_main.xml code is like

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".MainActivity"
   android:layout_gravity="center"
   android:gravity="center">

   <Button
       android:id="@+id/btn_save"
       android:layout_width="200dp"
       android:layout_height="wrap_content"
       android:layout_marginBottom="8dp"
       android:layout_marginTop="8dp"
       android:text="@string/save_data"/>
   <Button
       android:id="@+id/btn_get"
       android:layout_below="@id/btn_save"
       android:layout_width="200dp"
       android:layout_height="wrap_content"
       android:layout_marginBottom="8dp"
       android:layout_marginTop="8dp"
       android:text="@string/get_data" />
   <Button
       android:id="@+id/btn_delete"
       android:layout_below="@id/btn_get"
       android:layout_width="200dp"
       android:layout_height="wrap_content"
       android:layout_marginBottom="8dp"
       android:layout_marginTop="8dp"
       android:text="@string/delete_single_data" />
   <Button
       android:id="@+id/btn_clear"
       android:layout_below="@id/btn_delete"
       android:layout_width="200dp"
       android:layout_height="wrap_content"
       android:layout_marginBottom="8dp"
       android:layout_marginTop="8dp"
       android:text="@string/clear"/>

</RelativeLayout>
 

Step 13   -
Your MainActivity.java code is like

package com.shared.preferences;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.Map;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

   private Button btn_save, btn_get, btn_delete, btn_clear;
   private Context context = MainActivity.this;
   private SharedPreferences mPrefs;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);

       // method for find ids of views
       findIDs();

       // to maintian click listner of views
       initListner();

   }

   private void initListner() {
       btn_save.setOnClickListener(this);
       btn_get.setOnClickListener(this);
       btn_delete.setOnClickListener(this);
       btn_clear.setOnClickListener(this);

   }

   private void findIDs() {
       btn_save = findViewById(R.id.btn_save);
       btn_get = findViewById(R.id.btn_get);
       btn_delete = findViewById(R.id.btn_delete);
       btn_clear = findViewById(R.id.btn_clear);
   }

   /*
    * implement @View.OnClickListner to MainActivity class
    */
   @Override
   public void onClick(View view) {
       switch (view.getId()) {

           // when user click on "Save data" button
           case R.id.btn_save:
               Intent saveIntent = new Intent(MainActivity.this, SaveActivity.class);
               startActivity(saveIntent);
               break;
           case R.id.btn_get:
               Intent getIntent = new Intent(MainActivity.this, GetDataActivity.class);
               startActivity(getIntent);
               break;
           case R.id.btn_delete:
               mPrefs = context.getSharedPreferences(SaveActivity.MY_PREFERENCES, Context.MODE_PRIVATE);
               final ArrayList<String> allKey = new ArrayList<>();
               allKey.clear(); // for remove all previous data if exist

               ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(context, android.R.layout.simple_list_item_1, allKey);

               Map<String, ?> KEY = mPrefs.getAll();

               for (Map.Entry<String, ?> entry : KEY.entrySet()) {
                   allKey.add(entry.getKey());
               }

               if (allKey.size() != 0 ){
                   /*
                    *  To show all KEY which is stored in SharedPreference nad delete one KEY  from that
                    * */
                   AlertDialog.Builder choiceDialog = new AlertDialog.Builder(this);
                   choiceDialog.setTitle("Delete Key");
                   choiceDialog.setSingleChoiceItems(arrayAdapter, -1, new DialogInterface
                           .OnClickListener() {
                       public void onClick(DialogInterface dialog, final int item) {

                           SharedPreferences.Editor editor = mPrefs.edit();
                           /*
                            * To remove KEY from SharedPreferenec editor.remove(String s)
                            * */
                           editor.remove(allKey.get(item));
                           editor.apply();

                           dialog.dismiss();
                           Toast.makeText(context, "Removed KEY " + allKey.get(item), Toast.LENGTH_SHORT).show();
                       }
                   });
                   choiceDialog.create().show();
               }
               else {
                   Toast.makeText(context, "No stored KEY", Toast.LENGTH_SHORT).show();
               }


               break;
           case R.id.btn_clear:
               AlertDialog.Builder clearDialog = new AlertDialog.Builder(this);
               clearDialog.setTitle("Clear all KEY");
               clearDialog.setMessage("Are you sure you want to delete all KEY ?");
               clearDialog.setPositiveButton("Clear", new DialogInterface.OnClickListener() {
                   @Override
                   public void onClick(DialogInterface dialogInterface, int i) {
                       mPrefs = context.getSharedPreferences(SaveActivity.MY_PREFERENCES, Context.MODE_PRIVATE);
                       /*
                        * To delete KEY need to Editor or make any change
                        * */
                       SharedPreferences.Editor editor = mPrefs.edit();
                       /*
                        * To remove all KEY or clear SharedPreference from SharedPreference editor.remove(String s)
                        * */
                       editor.clear();
                       editor.apply();

                       dialogInterface.dismiss();
                       Toast.makeText(context, "Cleared SharedPreference", Toast.LENGTH_SHORT).show();
                   }
               });
               clearDialog.create().show();
               break;
       }
   }
}
 

Step 14   -
Your activity_save.xml code is like

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   xmlns:tools="http://schemas.android.com/tools"
   android:orientation="vertical"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".SaveActivity">

   <EditText
       android:id="@+id/et_username"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_marginBottom="8dp"
       android:layout_marginEnd="8dp"
       android:layout_marginLeft="8dp"
       android:layout_marginRight="8dp"
       android:layout_marginStart="8dp"
       android:maxLength="20"
       android:layout_marginTop="8dp"
       android:hint="@string/user_name"
       android:textColor="@android:color/black"
       android:textSize="16sp"
       android:paddingLeft="10dp" />
   <EditText
       android:id="@+id/et_age"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_marginBottom="8dp"
       android:maxLength="2"
       android:layout_marginEnd="8dp"
       android:layout_marginLeft="8dp"
       android:layout_marginRight="8dp"
       android:layout_marginStart="8dp"
       android:layout_marginTop="8dp"
       android:hint="@string/age"
       android:inputType="number"
       android:textColor="@android:color/black"
       android:textSize="16sp"
       android:paddingLeft="10dp" />
   <TextView
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="@string/hobbies"
       android:textSize="16sp"
       android:layout_marginEnd="8dp"
       android:layout_marginLeft="16dp"
       android:layout_marginRight="8dp"
       android:layout_marginStart="16dp"
       android:layout_marginTop="8dp"/>

   <LinearLayout
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_margin="16dp">
       <CheckBox
           android:layout_weight="1"
           android:id="@+id/cb_cricket"
           android:layout_width="0dp"
           android:layout_height="wrap_content"
           android:text="@string/cricket"
           android:textSize="16sp"/>
       <CheckBox
           android:layout_weight="1"
           android:id="@+id/cb_football"
           android:layout_width="0dp"
           android:layout_height="wrap_content"
           android:gravity=""
           android:text="@string/football"
           android:textSize="16sp"/>
       <CheckBox
           android:layout_weight="1"
           android:id="@+id/cb_hockey"
           android:layout_width="0dp"
           android:layout_height="wrap_content"
           android:text="@string/hockey"
           android:textSize="16sp"/>
   </LinearLayout>

   <Button
       android:id="@+id/btn_save_data"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:text="@string/save"
       android:layout_marginLeft="50dp"
       android:layout_marginRight="50dp"
       android:layout_marginStart="50dp"
       android:layout_marginEnd="50dp"
       android:layout_gravity="bottom"
       android:layout_marginTop="100dp"/>

</LinearLayout>
 

Step 15   -
Your SaveActivity.java code is like

package com.shared.preferences;

import android.content.Context;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
import com.google.gson.Gson;
import java.util.ArrayList;

public class SaveActivity extends AppCompatActivity implements View.OnClickListener {
   private EditText et_username, et_age;
   private CheckBox cb_cricket, cb_football, cb_hockey;
   private Button btn_save_data;
   private ArrayList<String> hobbies;
   private SharedPreferences  mPrefs;
   private Context context = SaveActivity.this;
   public static final String MY_PREFERENCES = "MyPref" ;
   public static final String UserName = "username" ;
   public static final String Age= "age";
   public static final String Hobbies= "hobbies";

   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_save);
       // initialize SharedPreference
       /*
       *  MY_PREFERENCES is your preference name
       *  MODE_PRIVATE -> By setting this mode, the file can only be accessed using calling application.
       *  MODE_WORLD_READABLE -> This mode allow other application to read the preferences.
       *  MODE_WORLD_WRITEABLE -> This mode allow other application to write the preferences.
       * */
       mPrefs = context.getSharedPreferences(MY_PREFERENCES, Context.MODE_PRIVATE);
       // method for find ids of views
       findIDs();
       // to maintain click listner of views
       initListner();

   }

   
private void initListner() {
       btn_save_data.setOnClickListener(this);
   }

   private void findIDs() {
       et_username = findViewById(R.id.et_username);
       et_age = findViewById(R.id.et_age);
       cb_cricket = findViewById(R.id.cb_cricket);
       cb_football = findViewById(R.id.cb_football);
       cb_hockey = findViewById(R.id.cb_hockey);
       btn_save_data = findViewById(R.id.btn_save_data);
   }

   @Override
   public void onClick(View view) {
       switch (view.getId()){
           case R.id.btn_save_data:
               /*  to check entered data is valid OR Is it empty?
               *  if it is valid then data saved into Shared preference otherwise it will give an error
               * */
               checkValidData();
               break;
       }
   }

   private void checkValidData() {
       String username = et_username.getText().toString().trim();
       String age = et_age.getText().toString().trim();
       boolean cricket = cb_cricket.isChecked();
       boolean football = cb_football.isChecked();
       boolean hockey = cb_hockey.isChecked();
       /*
       * if user doesn't fill up any value or doesn't check any check box
       * else users data will store in Shared preference
       * */
       if (username.length()==0 || age.length()==0 || !cricket && !football && !hockey ){
           if (username.length()==0){
               et_username.setError("Fill up user name");
           }
           if (age.length()==0){
               et_age.setError("Fill up age");
           }
           if (!cricket || !football || !hockey){
               Toast.makeText(this, "Select hobby/hobbies", Toast.LENGTH_SHORT).show();
           }
       }
       else {
           hobbies = new ArrayList<>();  // We will store hobbies into arraylist and store ArrayList into SharedPreference
           /* if cricket checkbox selected it will stored into ArrayList */
           if (cricket){
               hobbies.add(cb_cricket.getText().toString());
           }
           /* if football checkbox selected it will stored into ArrayList */
           if (football){
               hobbies.add(cb_football.getText().toString());
           }
           /* if hockey checkbox selected it will stored into ArrayList */
           if (hockey){
               hobbies.add(cb_hockey.getText().toString());
           }
           /* Calling seprate method for storing data into SharedPreference */
           saveToSharedPreference(username, age, hobbies);
       }
   }

   private void saveToSharedPreference(String username, String age, ArrayList<String> hobbies) {
       SharedPreferences.Editor editor = mPrefs.edit(); // Need a editor to put data into SharedPreference.

       // put String value
       editor.putString(UserName, username);
       // put Integer value
       editor.putInt(Age, Integer.parseInt(age)); // Integer.parseInt(int) -> for convert string value into integer value

       /*
       * To store ArrayList into SharedPreference you need to convert ArrayList into String format by Serialization
       * To convert ArrayList into String using GSON add library to you build.gradle
       * ToDo: into build.gradle
       * ToDo: implementation 'com.google.code.gson:gson:2.7'
       * */
       Gson gson = new Gson();
       String hobbiesString = gson.toJson(hobbies);
       editor.putString(Hobbies, hobbiesString);

       /*
       * editor.commit() -> writes its data to persistent storage immediately
       * editor.apply() -> will handle data in the background
       * */
       editor.apply();
       Toast.makeText(this, "Data saved successfully", Toast.LENGTH_SHORT).show();
       finish(); // finish the activity

   }
}
 

Step 16   -
Your activity_get_data.xml code is like

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   android:orientation="vertical"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".GetDataActivity">

   <LinearLayout
       android:id="@+id/lnr_data"
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       android:orientation="vertical"
       android:visibility="gone">

       <TextView
           android:id="@+id/txt_username"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:layout_gravity="center_horizontal"
           android:text="XYZ"
           android:textSize="16sp"
           android:layout_margin="16dp"/>

       <TextView
           android:id="@+id/txt_age"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:layout_gravity="center_horizontal"
           android:text="00"
           android:textSize="16sp"
           android:layout_margin="16dp"/>

       <ListView
           android:id="@+id/listView"
           android:layout_margin="40dp"
           android:layout_width="match_parent"
           android:layout_height="wrap_content" />

   </LinearLayout>

   <LinearLayout
       android:id="@+id/lnr_no_data"
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       android:gravity="center">

       <TextView
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:text="No data"
           android:textSize="20sp"/>

   </LinearLayout>

</LinearLayout>
 

Step 17   -
Your GetDataActivity.java code is like

package com.shared.preferences;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;

public class GetDataActivity extends AppCompatActivity {

   private ListView listView;
   private TextView txt_username, txt_age;
   private LinearLayout lnr_no_data, lnr_data;
   private Context context = GetDataActivity.this;
   private SharedPreferences mPrefs;
   private String username;
   private int age;
   private ArrayList<String> hobbies;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_get_data);

       mPrefs = context.getSharedPreferences(SaveActivity.MY_PREFERENCES, Context.MODE_PRIVATE);

       // method for find ids of views
       findIDs();
       if (getDataFromShredPreference()) {
           lnr_no_data.setVisibility(View.GONE);
           lnr_data.setVisibility(View.VISIBLE);
           txt_username.setText(username);
           txt_age.setText(String.valueOf(age)); // convert Integer value into String to set text
           /*
           * print hobbies into simple list view
           * */
           if (hobbies != null) {
               ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
                       android.R.layout.simple_list_item_1, android.R.id.text1, hobbies);
               listView.setAdapter(adapter);
           }
           else {
               listView.setVisibility(View.GONE);
           }
       }
       else {
           lnr_no_data.setVisibility(View.VISIBLE);
           lnr_data.setVisibility(View.GONE);
       }

   }

   private boolean getDataFromShredPreference() {
       /*
        * To check whether data exist or not
        * if data available it will return TRUE otherwise FALSE
        * */
       if (mPrefs.contains(SaveActivity.UserName) || mPrefs.contains(SaveActivity.Age) || mPrefs.contains(SaveActivity.Hobbies)) {
           /*
            * To get stored String value, it will return stored value if exist otherwise it will return second argument value.
            * */
           username = mPrefs.getString(SaveActivity.UserName, "");
           /*
            * To get stored Integer value, it will return stored value if exist otherwise it will return second arguments value.
            * */
           age = mPrefs.getInt(SaveActivity.Age, 0);
           /*
            * To get stored ArrayList value by De-serialization
            * Define Type of ArrayList<String>
            * */
           Gson gson = new Gson();
           String hobbiesString = mPrefs.getString(SaveActivity.Hobbies, "");
           if (!hobbiesString.equalsIgnoreCase("")) {
               Type type = new TypeToken<ArrayList<String>>() {
               }.getType();
               hobbies = gson.fromJson(hobbiesString, type);
           }
           return true;
       } else {
           return false;
       }
   }

   private void findIDs() {
       txt_username = findViewById(R.id.txt_username);
       txt_age = findViewById(R.id.txt_age);
       listView = findViewById(R.id.listView);
       lnr_no_data = findViewById(R.id.lnr_no_data);
       lnr_data = findViewById(R.id.lnr_data);
   }
}

Got an Idea of Game Development? What are you still waiting for? Contact us now and see the Idea live soon. Our company has been named as one of the best Game Development Company in India.

I am mobile app developer. I am working on android. I love to share designing tips & tricks with you.

Download demo of this blog click on Download button.