{"id":385,"date":"2015-12-30T06:46:01","date_gmt":"2015-12-30T06:46:01","guid":{"rendered":"http:\/\/abhiandroid.com\/programming\/?page_id=385"},"modified":"2018-06-06T04:45:42","modified_gmt":"2018-06-06T04:45:42","slug":"shared-preference","status":"publish","type":"page","link":"https:\/\/abhiandroid.com\/programming\/shared-preference","title":{"rendered":"Shared Preference Tutorial With Example In Android Studio"},"content":{"rendered":"<p>Shared Preference in Android are used to save data based on key-value pair. If we go deep into understanding of word: shared means to distribute data within and preference means something important or preferable, so SharedPreferences data is shared and preferred data.<\/p>\n<p>Shared Preference can be used to save primitive data type: string, long, int, float and Boolean.<\/p>\n<p><span style=\"color: #008000;\"><strong>What Is Preference File?<\/strong><\/span><\/p>\n<p>Before we begin explaining shared preference, it is important to understand preference file.<\/p>\n<p>A preference file is actually a xml file saved in internal memory of device. Every application have some data stored in memory in a directory data\/data\/application package name i.e data\/data\/com.abhiandroid.abhiapp so whenever getSharedPreferences(String name,int mode) function get called it validates the file that if it exists or it doesn\u2019t then a new xml is created with passed name.<\/p>\n<hr \/>\n<h4><strong>Two Ways To Save Data Through Shared Preference:<\/strong><\/h4>\n<p>There are two different ways to save data in Android through Shared Preferences &#8211; One is using Activity based preferences and other is creating custom preferences.<\/p>\n<p><span style=\"color: #008000;\"><strong><span style=\"text-decoration: underline;\">Activity Preferences:<\/span> <\/strong><\/span><\/p>\n<ul>\n<li>For activity preferences developer have to call function <strong>getPreferences (int mode)<\/strong> available in Activity class<\/li>\n<li>Use only when one preference file is needed in Activity<\/li>\n<li>It doesn&#8217;t require name as it will be the only preference file for this activity<\/li>\n<li>Developer doesn&#8217;t usually prefer using this even if they need only one preference file in Activity. They prefer using custom getSharedPreferences(String name,int mode).<\/li>\n<\/ul>\n<p>To use activity preferences developer have to call function <strong>getPreferences (int mode)<\/strong> available in Activity class. The function getPreferences(int mode) call the other function used to create custom preferences i.e getSharedPreferences(String name,int mode). Just because Activity contains only one preference file so getPreferences(int mode) function simply pass the name of Activity class to create a preference file.<\/p>\n<p><span style=\"color: #ff0000;\"><strong>Important Note:<\/strong><\/span> Mode are discussed in Custom preferences.<\/p>\n<p><span style=\"text-decoration: underline; color: #008000;\"><strong>Custom Preferences:<\/strong><\/span><\/p>\n<ul>\n<li>Developer needs to use <strong>getSharedPreferences(String name,int mode)<\/strong> for custom preferences<\/li>\n<li>Used in cases when more than one preference file required in Activity<\/li>\n<li>Name of the preference file is passed in first parameter<\/li>\n<\/ul>\n<p>Custom Preferences can be created by calling function <strong>getSharedPreferences(String name,int mode)<\/strong>, it can be called from anywhere in the application with reference of <strong>Context. <\/strong>Here name is any preferred name for example: User,Book etc. and mode is used to set kind of privacy for file.<\/p>\n<hr \/>\n<h4><strong>Mode And Its Type In Shared Preference<\/strong>:<\/h4>\n<p>To create activity based preferences or custom preferences developer have to pass mode to let the system know about privacy of preference file.<\/p>\n<p><strong>Before we begin a brief discussion on Context <\/strong><\/p>\n<p>Context is an abstract class used to get global information in Android Application resources like strings, values, drawables, assets etc. Here modes are declared and static final constant in Context class.<\/p>\n<p><span style=\"color: #008000;\"><strong>There are three types of Mode in Shared Preference:<\/strong><\/span><\/p>\n<ol>\n<li><strong>Context.MODE_PRIVATE &#8211; default value (Not accessible outside of your application)<br \/>\n<\/strong><\/li>\n<li><strong>Context.MODE_WORLD_READABLE &#8211; readable to other apps<\/strong><\/li>\n<li><strong>Context.MODE_WORLD_WRITEABLE &#8211; read\/write to other apps<\/strong><\/li>\n<\/ol>\n<p><span style=\"color: #008000;\"><strong>MODE_PRIVATE &#8211; <\/strong><\/span>It is a default mode. MODE_PRIVATE means that when any preference file is created with private mode then it will not be accessible outside of your application. This is the most common mode which is used.<\/p>\n<p><strong><span style=\"color: #008000;\">MODE_WORLD_READABLE &#8211;<\/span> <\/strong>If developer creates a shared preference file using mode world readable then it can be read by anyone who knows it\u2019s name, so any other outside application can easily read data of your app. This mode is very rarely used in App.<\/p>\n<p><span style=\"color: #008000;\"><strong>MODE_WORLD_WRITEABLE &#8211; <\/strong><\/span>It\u2019s similar to mode world readable but with both kind of accesses i.e read and write. This mode is never used in App by Developer.<\/p>\n<hr \/>\n<h4><strong>Important Google Recommend Naming Convention For Preference File:<\/strong><\/h4>\n<p>Please make sure to follow recommendation by Google while giving preference file name. Google recommends to give name as application package name + preferred name.<\/p>\n<p>For example: if your application package name is <code>com.abhiandroid.abhiapp<\/code> then preference could be <code>com.abhiandroid.abhiapp.User<\/code> where <code>com.abhiandroid.abhiapp.User<\/code> is the name of preference file.<\/p>\n<hr \/>\n<h4><strong>Creating Shared Preference:<\/strong><\/h4>\n<p>As discussed above, to create shared preference developer needs to call <strong>getPreferences(int mode)<\/strong> or <strong>getSharedPreferences(String name,int mode)<\/strong> method. Both of the function return SharedPreferences object to deal with save and get values from preference file.<\/p>\n<p>SharedPreferences is a singleton class means this class will only have a single object throughout the application lifecycle. However there can multiple preference files so all the preference files can be read and write using SharedPreferences class.<\/p>\n<hr \/>\n<h4><strong>Save Data In SharedPreferences:<\/strong><\/h4>\n<p><span style=\"color: #008000;\"><strong>Step 1:<\/strong><\/span><\/p>\n<p>To save data in SharedPreferences developer need to called <strong>edit()<\/strong> function of SharedPreferences class which returns <strong>Editor<\/strong> class object.<\/p>\n<p><span style=\"color: #008000;\"><strong>Step 2:<\/strong><\/span><\/p>\n<p><strong>Editor <\/strong>class provide different function to save primitive time data. For example, Editor have all primitive data function including String type data as <strong>putInt(String keyName,int value).<\/strong><\/p>\n<p>Common primitive function format is: <strong>put + Primitive Type name (String keyname, Primitive Type value)<\/strong><\/p>\n<p><span style=\"color: #008000;\"><strong>Step 3:<\/strong><\/span><\/p>\n<p>Now make sure that key name should be unique for any values you save otherwise it will be overrided. To exactly save the values you put in different primitive functions you must call <strong>commit()<\/strong> function of Editor.<\/p>\n<hr \/>\n<h4><strong>Read or get data from SharedPreferences<\/strong><\/h4>\n<p><span style=\"color: #008000;\"><strong>Step 1:<\/strong><\/span> To read data first developer have to get reference of SharedPreferences object by calling <strong>getPreferences (int mode) <\/strong> or <strong>getSharedPreferences (String name,int mode)<\/strong>.<\/p>\n<p><span style=\"color: #008000;\"><strong>Step 2:<\/strong><\/span> Then developer can get values using SharedPreferences object by calling different primitive type function starting with get+Primitive Type name. Here every function has an additional parameter for every Primitive Type as default value in case there is no value found corresponding to passed key.<\/p>\n<p>For example, to get saved int value just call <strong>getInt(&#8220;GameScore&#8221;,-1) <\/strong>function where &#8220;GameScore&#8221; is key and -1 is a default value in case no value was saved for GameScore.<\/p>\n<hr \/>\n<h4><strong>Remove Data Or Clear All Data<\/strong><\/h4>\n<p>Similar to save data there is a function <strong>remove(String key)<\/strong> in <code>SharedPreferences.Editor<\/code> to remove a particular key based data from preference file<\/p>\n<p>To clear all data just call function <strong>clear() <\/strong>available in <code>SharedPreferences.Editor<\/code>. Make sure to call <strong>commit()<\/strong> method to save changes. So clear data will never delete the preference file but make it empty.<\/p>\n<hr \/>\n<h4><strong>Code Of Saving &amp; Retrieving Data in Shared Preference:<\/strong><\/h4>\n<pre>public static final String PREFS_GAME =\"com.abhiandroid.abhiapp.GamePlay\";\r\npublic static final String GAME_SCORE= \"GameScore\";\r\n\r\n\/\/======== Code to save data ===================\r\n\r\nSharedPreferences sp = getSharedPreferences(PREFS_GAME ,Context.MODE_PRIVATE);\r\nsp.edit().putInt(GAME_SCORE,100).commit();\r\n\r\n\/\/========= Code to get saved\/ retrieve data ==============\r\n\r\nSharedPreferences sp = getSharedPreferences(PREFS_GAME ,Context.MODE_PRIVATE);\r\nint sc  = sp.getInt(GAME_SCORE,0);\r\nLog.d(\"AbhiAndroid\",\"achieved score  is \"+ sc);<\/pre>\n<hr \/>\n<h4><strong>Shared Preference Example:<\/strong><\/h4>\n<p>Let&#8217;s use Shared Preference for a very basic purpose of saving login details of a person i.e. email and password on his device. So he don&#8217;t have to re-enter his login details every time he opens the App.<\/p>\n<p>Below is the final output we will create and use Shared Preference to save Signin Details:<\/p>\n<p><center><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-435\" src=\"\/programming\/wp-content\/uploads\/2015\/12\/Shared-Preference-Example-Final-Output.jpg\" alt=\"Shared Preference Example Final Output\" width=\"354\" height=\"680\" srcset=\"https:\/\/abhiandroid.com\/programming\/wp-content\/uploads\/2015\/12\/Shared-Preference-Example-Final-Output.jpg 354w, https:\/\/abhiandroid.com\/programming\/wp-content\/uploads\/2015\/12\/Shared-Preference-Example-Final-Output-156x300.jpg 156w\" sizes=\"auto, (max-width: 354px) 100vw, 354px\" \/><\/center><span style=\"color: #008000;\"><strong>Step 1:<\/strong><\/span> Create a new project and create an login Activity activity_login.xml. In this create a login UI asking user email and password with an option of remember me checkbox. Also a button displaying Signin or Register.<\/p>\n<p>Below is the complete code login UI activity_login.xml<\/p>\n<pre>&lt;LinearLayout xmlns:android=\"http:\/\/schemas.android.com\/apk\/res\/android\"\r\n              xmlns:tools=\"http:\/\/schemas.android.com\/tools\"\r\n              android:layout_width=\"match_parent\"\r\n              android:layout_height=\"match_parent\"\r\n              android:gravity=\"center_horizontal\"\r\n              android:orientation=\"vertical\"\r\n              android:paddingBottom=\"@dimen\/activity_vertical_margin\"\r\n              android:paddingLeft=\"@dimen\/activity_horizontal_margin\"\r\n              android:paddingRight=\"@dimen\/activity_horizontal_margin\"\r\n              android:paddingTop=\"@dimen\/activity_vertical_margin\"\r\n              tools:context=\"com.samplesharedpreferences.LoginActivity\"&gt;\r\n\r\n    &lt;!-- Login progress --&gt;\r\n    &lt;ProgressBar\r\n        android:id=\"@+id\/login_progress\"\r\n        style=\"?android:attr\/progressBarStyleLarge\"\r\n        android:layout_width=\"wrap_content\"\r\n        android:layout_height=\"wrap_content\"\r\n        android:layout_marginBottom=\"8dp\"\r\n        android:visibility=\"gone\"\/&gt;\r\n\r\n    &lt;ScrollView\r\n        android:id=\"@+id\/login_form\"\r\n        android:layout_width=\"match_parent\"\r\n        android:layout_height=\"match_parent\"&gt;\r\n\r\n        &lt;LinearLayout\r\n            android:id=\"@+id\/email_login_form\"\r\n            android:layout_width=\"match_parent\"\r\n            android:layout_height=\"wrap_content\"\r\n            android:orientation=\"vertical\"&gt;\r\n\r\n            &lt;android.support.design.widget.TextInputLayout\r\n                android:layout_width=\"match_parent\"\r\n                android:layout_height=\"wrap_content\"&gt;\r\n\r\n                &lt;EditText\r\n                    android:id=\"@+id\/email\"\r\n                    android:layout_width=\"match_parent\"\r\n                    android:layout_height=\"wrap_content\"\r\n                    android:hint=\"@string\/prompt_email\"\r\n                    android:inputType=\"textEmailAddress\"\r\n                    android:maxLines=\"1\"\r\n                    android:singleLine=\"true\"\/&gt;\r\n\r\n            &lt;\/android.support.design.widget.TextInputLayout&gt;\r\n\r\n            &lt;android.support.design.widget.TextInputLayout\r\n                android:layout_width=\"match_parent\"\r\n                android:layout_height=\"wrap_content\"&gt;\r\n\r\n                &lt;EditText\r\n                    android:id=\"@+id\/password\"\r\n                    android:layout_width=\"match_parent\"\r\n                    android:layout_height=\"wrap_content\"\r\n                    android:hint=\"@string\/prompt_password\"\r\n                    android:imeActionId=\"@+id\/login\"\r\n                    android:imeActionLabel=\"@string\/action_sign_in_short\"\r\n                    android:imeOptions=\"actionUnspecified\"\r\n                    android:inputType=\"textPassword\"\r\n                    android:maxLines=\"1\"\r\n                    android:singleLine=\"true\"\/&gt;\r\n\r\n            &lt;\/android.support.design.widget.TextInputLayout&gt;\r\n\r\n            &lt;CheckBox\r\n                android:layout_width=\"match_parent\"\r\n                android:layout_height=\"wrap_content\"\r\n                android:text=\"Remember Me\"\r\n                android:id=\"@+id\/checkBoxRememberMe\"\/&gt;\r\n\r\n            &lt;Button\r\n                android:id=\"@+id\/email_sign_in_button\"\r\n                style=\"?android:textAppearanceSmall\"\r\n                android:layout_width=\"match_parent\"\r\n                android:layout_height=\"wrap_content\"\r\n                android:layout_marginTop=\"16dp\"\r\n                android:text=\"@string\/action_sign_in\"\r\n                android:textStyle=\"bold\"\/&gt;\r\n\r\n        &lt;\/LinearLayout&gt;\r\n    &lt;\/ScrollView&gt;\r\n&lt;\/LinearLayout&gt;<\/pre>\n<p><span style=\"color: #008000;\"><strong>Step 2:<\/strong><\/span> Now lets code the LoginActivity.java where we will create a Login form. Below is the complete code of LoginActivity.java with explanation included in comment.<\/p>\n<pre>package com.samplesharedpreferences;\r\n\r\nimport android.animation.Animator;\r\nimport android.animation.AnimatorListenerAdapter;\r\nimport android.annotation.TargetApi;\r\nimport android.content.Context;\r\nimport android.content.Intent;\r\nimport android.content.SharedPreferences;\r\nimport android.content.pm.PackageManager;\r\nimport android.support.annotation.NonNull;\r\nimport android.support.design.widget.Snackbar;\r\nimport android.support.v7.app.AppCompatActivity;\r\nimport android.app.LoaderManager.LoaderCallbacks;\r\nimport android.content.ContentResolver;\r\nimport android.content.CursorLoader;\r\nimport android.content.Loader;\r\nimport android.database.Cursor;\r\nimport android.net.Uri;\r\nimport android.os.AsyncTask;\r\nimport android.os.Build.VERSION;\r\nimport android.os.Build;\r\nimport android.os.Bundle;\r\nimport android.provider.ContactsContract;\r\nimport android.text.TextUtils;\r\nimport android.view.KeyEvent;\r\nimport android.view.View;\r\nimport android.view.View.OnClickListener;\r\nimport android.view.inputmethod.EditorInfo;\r\nimport android.widget.ArrayAdapter;\r\nimport android.widget.AutoCompleteTextView;\r\nimport android.widget.Button;\r\nimport android.widget.CheckBox;\r\nimport android.widget.EditText;\r\nimport android.widget.TextView;\r\n\r\nimport java.util.ArrayList;\r\nimport java.util.List;\r\n\r\nimport static android.Manifest.permission.READ_CONTACTS;\r\n\r\n\/**\r\n * A login screen that offers login via email\/password.\r\n *\/\r\npublic class LoginActivity extends AppCompatActivity {\r\n\r\n\r\n    \/\/ UI references.\r\n    private EditText mEmailView;\r\n    private EditText mPasswordView;\r\n\r\n    private CheckBox checkBoxRememberMe;\r\n\r\n    @Override\r\n    protected void onCreate(Bundle savedInstanceState) {\r\n        super.onCreate(savedInstanceState);\r\n        setContentView(R.layout.activity_login);\r\n        \/\/ Set up the login form.\r\n        mEmailView = (EditText) findViewById(R.id.email);\r\n        mPasswordView = (EditText) findViewById(R.id.password);\r\n        mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {\r\n            @Override\r\n            public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {\r\n                if (id == R.id.login || id == EditorInfo.IME_NULL) {\r\n                    attemptLogin();\r\n                    return true;\r\n                }\r\n                return false;\r\n            }\r\n        });\r\n\r\n        Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);\r\n        mEmailSignInButton.setOnClickListener(new OnClickListener() {\r\n            @Override\r\n            public void onClick(View view) {\r\n                attemptLogin();\r\n            }\r\n        });\r\n\r\n        checkBoxRememberMe = (CheckBox) findViewById(R.id.checkBoxRememberMe);\r\n        \/\/Here we will validate saved preferences\r\n        if (!new PrefManager(this).isUserLogedOut()) {\r\n            \/\/user's email and password both are saved in preferences\r\n            startHomeActivity();\r\n        }\r\n\r\n    }\r\n\r\n\r\n    \/**\r\n     * Attempts to sign in or register the account specified by the login form.\r\n     * If there are form errors (invalid email, missing fields, etc.), the\r\n     * errors are presented and no actual login attempt is made.\r\n     *\/\r\n    private void attemptLogin() {\r\n\r\n        \/\/ Reset errors.\r\n        mEmailView.setError(null);\r\n        mPasswordView.setError(null);\r\n\r\n        \/\/ Store values at the time of the login attempt.\r\n        String email = mEmailView.getText().toString();\r\n        String password = mPasswordView.getText().toString();\r\n\r\n        boolean cancel = false;\r\n        View focusView = null;\r\n\r\n        \/\/ Check for a valid password, if the user entered one.\r\n        if (!TextUtils.isEmpty(password) &amp;&amp; !isPasswordValid(password)) {\r\n            mPasswordView.setError(getString(R.string.error_invalid_password));\r\n            focusView = mPasswordView;\r\n            cancel = true;\r\n        }\r\n\r\n        \/\/ Check for a valid email address.\r\n        if (TextUtils.isEmpty(email)) {\r\n            mEmailView.setError(getString(R.string.error_field_required));\r\n            focusView = mEmailView;\r\n            cancel = true;\r\n        } else if (!isEmailValid(email)) {\r\n            mEmailView.setError(getString(R.string.error_invalid_email));\r\n            focusView = mEmailView;\r\n            cancel = true;\r\n        }\r\n\r\n        if (cancel) {\r\n            \/\/ There was an error; don't attempt login and focus the first\r\n            \/\/ form field with an error.\r\n            focusView.requestFocus();\r\n        } else {\r\n            \/\/ save data in local shared preferences\r\n            if (checkBoxRememberMe.isChecked())\r\n                saveLoginDetails(email, password);\r\n            startHomeActivity();\r\n        }\r\n    }\r\n\r\n    private void startHomeActivity() {\r\n        Intent intent = new Intent(this, HomeActivity.class);\r\n        startActivity(intent);\r\n        finish();\r\n    }\r\n\r\n    private void saveLoginDetails(String email, String password) {\r\n        new PrefManager(this).saveLoginDetails(email, password);\r\n    }\r\n\r\n\r\n    private boolean isEmailValid(String email) {\r\n        \/\/TODO: Replace this with your own logic\r\n        return email.contains(\"@\");\r\n    }\r\n\r\n    private boolean isPasswordValid(String password) {\r\n        \/\/TODO: Replace this with your own logic\r\n        return password.length() &gt; 4;\r\n    }\r\n}\r\n\r\n<\/pre>\n<p><span style=\"color: #008000;\"><strong>Step 3:<\/strong><\/span> Create a new java class for Shared Preference PrefManager. Below is the code of PrefManager.java<\/p>\n<pre>package com.samplesharedpreferences;\r\n\r\nimport android.content.Context;\r\nimport android.content.SharedPreferences;\r\n\r\n\/**\r\n * Class for Shared Preference\r\n *\/\r\npublic class PrefManager {\r\n\r\n    Context context;\r\n\r\n    PrefManager(Context context) {\r\n        this.context = context;\r\n    }\r\n\r\n    public void saveLoginDetails(String email, String password) {\r\n        SharedPreferences sharedPreferences = context.getSharedPreferences(\"LoginDetails\", Context.MODE_PRIVATE);\r\n        SharedPreferences.Editor editor = sharedPreferences.edit();\r\n        editor.putString(\"Email\", email);\r\n        editor.putString(\"Password\", password);\r\n        editor.commit();\r\n    }\r\n\r\n    public String getEmail() {\r\n        SharedPreferences sharedPreferences = context.getSharedPreferences(\"LoginDetails\", Context.MODE_PRIVATE);\r\n        return sharedPreferences.getString(\"Email\", \"\");\r\n    }\r\n\r\n    public boolean isUserLogedOut() {\r\n        SharedPreferences sharedPreferences = context.getSharedPreferences(\"LoginDetails\", Context.MODE_PRIVATE);\r\n        boolean isEmailEmpty = sharedPreferences.getString(\"Email\", \"\").isEmpty();\r\n        boolean isPasswordEmpty = sharedPreferences.getString(\"Password\", \"\").isEmpty();\r\n        return isEmailEmpty || isPasswordEmpty;\r\n    }\r\n}<\/pre>\n<p><span style=\"color: #008000;\"><strong>Step 4:<\/strong><\/span> Design the simple Home UI where we will display Welcome message along with his saved email address in Shared preference. Below is the code of content_home.xml<\/p>\n<pre>&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\r\n&lt;RelativeLayout\r\n    xmlns:android=\"http:\/\/schemas.android.com\/apk\/res\/android\"\r\n    xmlns:app=\"http:\/\/schemas.android.com\/apk\/res-auto\"\r\n    xmlns:tools=\"http:\/\/schemas.android.com\/tools\"\r\n    android:layout_width=\"match_parent\"\r\n    android:layout_height=\"match_parent\"\r\n    android:paddingBottom=\"@dimen\/activity_vertical_margin\"\r\n    android:paddingLeft=\"@dimen\/activity_horizontal_margin\"\r\n    android:paddingRight=\"@dimen\/activity_horizontal_margin\"\r\n    android:paddingTop=\"@dimen\/activity_vertical_margin\"\r\n    app:layout_behavior=\"@string\/appbar_scrolling_view_behavior\"\r\n    tools:context=\"com.samplesharedpreferences.HomeActivity\"\r\n    tools:showIn=\"@layout\/activity_home\"&gt;\r\n\r\n    &lt;TextView\r\n        android:id=\"@+id\/textViewUser\"\r\n        android:layout_width=\"wrap_content\"\r\n        android:layout_height=\"wrap_content\"\r\n        android:layout_centerInParent=\"true\"\r\n        android:gravity=\"center\"\r\n        android:text=\"Welcome\"\/&gt;\r\n\r\n\r\n&lt;\/RelativeLayout&gt;<\/pre>\n<p><span style=\"color: #008000;\"><strong>Step 5:<\/strong><\/span> Manifest file<\/p>\n<p>Make sure in your AndroidManifest.xml Intent Filter for Main and Launcher is set inside .LoginActivity because then only that Activity will open first.<\/p>\n<pre>&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\r\n&lt;manifest package=\"com.samplesharedpreferences\"\r\n          xmlns:android=\"http:\/\/schemas.android.com\/apk\/res\/android\"&gt;\r\n\r\n    &lt;!-- To auto-complete the email text field in the login form with the user's emails --&gt;\r\n    &lt;uses-permission android:name=\"android.permission.GET_ACCOUNTS\"\/&gt;\r\n    &lt;uses-permission android:name=\"android.permission.READ_PROFILE\"\/&gt;\r\n    &lt;uses-permission android:name=\"android.permission.READ_CONTACTS\"\/&gt;\r\n\r\n    &lt;application\r\n        android:allowBackup=\"true\"\r\n        android:icon=\"@mipmap\/ic_launcher\"\r\n        android:label=\"@string\/app_name\"\r\n        android:supportsRtl=\"true\"\r\n        android:theme=\"@style\/AppTheme\"&gt;\r\n        &lt;activity\r\n            android:name=\".LoginActivity\"\r\n            android:label=\"@string\/app_name\"&gt;\r\n            &lt;intent-filter&gt;\r\n                &lt;action android:name=\"android.intent.action.MAIN\"\/&gt;\r\n\r\n                &lt;category android:name=\"android.intent.category.LAUNCHER\"\/&gt;\r\n            &lt;\/intent-filter&gt;\r\n        &lt;\/activity&gt;\r\n        &lt;activity\r\n            android:name=\".HomeActivity\"\r\n            android:label=\"@string\/title_activity_home\"\r\n            android:theme=\"@style\/AppTheme.NoActionBar\"&gt;\r\n        &lt;\/activity&gt;\r\n    &lt;\/application&gt;\r\n\r\n&lt;\/manifest&gt;<\/pre>\n<p><span style=\"text-decoration: underline;\"><strong>Output:<\/strong><\/span><\/p>\n<p><span style=\"color: #008000;\"><strong>Step 1:<\/strong><\/span> Now run the App in Emulator. You will see the below output screen<\/p>\n<p><center><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-436\" src=\"\/programming\/wp-content\/uploads\/2015\/12\/Shared-Preference-Example-Output-screen-for-log-in.jpg\" alt=\"Shared Preference Example Output screen for log in\" width=\"354\" height=\"366\" srcset=\"https:\/\/abhiandroid.com\/programming\/wp-content\/uploads\/2015\/12\/Shared-Preference-Example-Output-screen-for-log-in.jpg 354w, https:\/\/abhiandroid.com\/programming\/wp-content\/uploads\/2015\/12\/Shared-Preference-Example-Output-screen-for-log-in-290x300.jpg 290w\" sizes=\"auto, (max-width: 354px) 100vw, 354px\" \/><\/center><span style=\"color: #008000;\"><strong>Step 2:<\/strong><\/span> Fill the email, password and click on remember me checkbox. In our case we have filled info@abhiandroid.com and abhiandroid.<\/p>\n<p><center><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-437\" src=\"\/programming\/wp-content\/uploads\/2015\/12\/Shared-Preference-Example-Login-Details-Filled.jpg\" alt=\"Shared Preference Example Login Details Filled\" width=\"376\" height=\"374\" srcset=\"https:\/\/abhiandroid.com\/programming\/wp-content\/uploads\/2015\/12\/Shared-Preference-Example-Login-Details-Filled.jpg 376w, https:\/\/abhiandroid.com\/programming\/wp-content\/uploads\/2015\/12\/Shared-Preference-Example-Login-Details-Filled-150x150.jpg 150w, https:\/\/abhiandroid.com\/programming\/wp-content\/uploads\/2015\/12\/Shared-Preference-Example-Login-Details-Filled-300x298.jpg 300w\" sizes=\"auto, (max-width: 376px) 100vw, 376px\" \/><\/center><span style=\"color: #008000;\"><strong>Step 3:<\/strong><\/span> It will display you the welcome message along with your email ID. Now close the App and reopen it. You will see the same message of Welcome and your email address printed. So here we have stored your email address on your device itself using Shared Preference.<\/p>\n<p><center><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-438\" src=\"\/programming\/wp-content\/uploads\/2015\/12\/Shared-Preference-Signin-Details-Saved-On-Device.jpg\" alt=\"Shared Preference Signin Details Saved On Device\" width=\"347\" height=\"391\" srcset=\"https:\/\/abhiandroid.com\/programming\/wp-content\/uploads\/2015\/12\/Shared-Preference-Signin-Details-Saved-On-Device.jpg 347w, https:\/\/abhiandroid.com\/programming\/wp-content\/uploads\/2015\/12\/Shared-Preference-Signin-Details-Saved-On-Device-266x300.jpg 266w\" sizes=\"auto, (max-width: 347px) 100vw, 347px\" \/><\/center><\/p>\n<hr \/>\n<h4><strong>Importance:<\/strong><\/h4>\n<p>During application development there are many situation where we need to store or save some data in a file. So rather than creating your own file and then managing it, Android provides mechanism to save data using SharedPreferences. To save some little amount of data SharedPreferences can be used like username and password of user, However if there is need to save large amount of data the always prefer to save data using <strong>sqlite<\/strong>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Shared Preference in Android are used to save data based on key-value pair. If we go deep into understanding of word: shared means to distribute data within and preference means something important or preferable, so SharedPreferences data is shared and preferred data. Shared Preference can be used to save primitive data type: string, long, int, &hellip; <a href=\"https:\/\/abhiandroid.com\/programming\/shared-preference\" class=\"more-link\">Continue reading <span class=\"screen-reader-text\">Shared Preference Tutorial With Example In Android Studio<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"parent":0,"menu_order":0,"comment_status":"open","ping_status":"closed","template":"home.php","meta":{"footnotes":""},"class_list":["post-385","page","type-page","status-publish","hentry"],"psp_head":"<title>Shared Preference Tutorial With Example In Android Studio \u2013 Abhi Android<\/title>\r\n<meta name=\"description\" content=\"Tutorial on Shared Preference with example and code in Android Studio. Learn about its mode, preference file and Editor class. Also find code for saving and retrieving data in Shared Preference.\" \/>\r\n<meta name=\"robots\" content=\"index,follow\" \/>\r\n<link rel=\"canonical\" href=\"https:\/\/abhiandroid.com\/programming\/shared-preference\" \/>\r\n","_links":{"self":[{"href":"https:\/\/abhiandroid.com\/programming\/wp-json\/wp\/v2\/pages\/385","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/abhiandroid.com\/programming\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/abhiandroid.com\/programming\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/abhiandroid.com\/programming\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/abhiandroid.com\/programming\/wp-json\/wp\/v2\/comments?post=385"}],"version-history":[{"count":1,"href":"https:\/\/abhiandroid.com\/programming\/wp-json\/wp\/v2\/pages\/385\/revisions"}],"predecessor-version":[{"id":909,"href":"https:\/\/abhiandroid.com\/programming\/wp-json\/wp\/v2\/pages\/385\/revisions\/909"}],"wp:attachment":[{"href":"https:\/\/abhiandroid.com\/programming\/wp-json\/wp\/v2\/media?parent=385"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}