New Post has been published on Simplified Coding
New Post has been published on https://www.simplifiedcoding.net/android-sharedpreferences-example/
Android SharedPreferences Example - Writing and Reading Values
SharedPreferences are using in Android to store data in Key-Value pairs. In this post we will see simple Android SharedPreferences Example. We will learn storing values to SharedPreferences, and Reading them back in the application. We will also see how to update and delete the values in SharedPreferences.
Contents
1 Android SharedPreferences
2 When to use SharedPreferences?
3 Accessing SharedPreferences
4 SharedPreferences Modes
5 Saving Values to SharedPreferences
5.1 #1 Get the SharedPreferences
5.2 #2 Initializing the Editor
5.3 #3 Put the values
5.4 #4 Apply the changes
6 Getting Values Back from SharedPreferences
6.1 #1 Get SharedPreferences
6.2 #2 Get Values
7 Modifying Values
8 Deleting Values
8.1 #1 Deleting a specific value
8.2 #2 Deleting Everything
9 Android SharedPreferences Example
9.1 Creating a Project
9.2 Creating User Interface
9.3 Saving and Reading Values
Android SharedPreferences
We have a class named SharedPreferences in android. It allows us a framework that helps in saving and retrieving persistent key value pairs of primitive datatypes. So remember the limitations of using Android SharedPreferences, it only allows primitive data types. The values are saved even when the application is killed.
When to use SharedPreferences?
As the name suggests, it is used to store preferences i.e user specific data, like settings, login sessions etc. You may find this Android Login and Registration tutorial helpful where we are using SharedPreferences to maintain a user Login Session.
Accessing SharedPreferences
Accessing SharedPreferences is very easy we can use the following methods and it will give us an instance of the SharedPreferences class.
Method Description SharedPreferences getSharedPreferences(String, int) This method can be called from inside and Activity or from the Context object.
It takes two parameters, the first parameter is a String and it is the name of the SharedPreferences that we want to get. If we already have a SharedPreferences of the specified name it will return us that. But if we don’t have any existing SharedPrferences of the specified name it will create one and will return the instance of SharedPreferences class. The second parameter defines the mode of the preference, it can be private to the activity or shared.
We use this method when we want multiple SharedPreferences for our application, specified by different name.
SharedPreferences getPreferences(int mode) It does the same thing as getSharedPreferences() but here we don’t need to supply a name. We use it only when we want a Single SharedPreferences that is the default one for the application.
SharedPreferences Modes
Mode Description MODE_PRIVATE This mode will make the shared preferences private to the application. MODE_WORLD_READABLE As the name suggest it is world readable, and it might be the reason for the security loop holes in your application. So you should use this mode with extra care. MODE_WORLD_WRITEABLE As the name suggest it is world writable, so it is even more dangerous then the world readable mode. So you should use this mode with extra care. MODE_MULTI_PROCESS It is deprecated from API 23, so we should not use it.. MODE_APPEND If you don’t want to destroy your existing preferences you can use this mode to append the preferences with your existing one.
Saving Values to SharedPreferences
Now lets see how do we save values in SharedPreferences. Remember only primitive data types can be saved. (Though with a little trick you can save anything).
We have the following steps to save values in SharedPreferences.
Get the SharedPreferences
Initialize the Editor
Put the values
Apply the changes
#1 Get the SharedPreferences
Inside your activity we will call the method getSharedPreferences().
//getting shared preferences SharedPreferences sp = getSharedPreferences("your_shared_pref_name", MODE_PRIVATE);
#2 Initializing the Editor
Now the following line will initialize the editor where we will put the values to be saved, in key-value pairs.
//initializing editor SharedPreferences.Editor editor = sp.edit();
#3 Put the values
We have the method putDataType() inside the editor. It can be putString, putInt, putChar and you can use the same for every data type that we have. The method takes two arguments first is the key and the second is the respective value. Key is always string and the second parameter is the data that we want to save. If we are using putString then second parameter would be a String.
editor.putString("stringkey", "value"); editor.putBoolean("boolkey", true); editor.putFloat("floatkey", 4.3434f); editor.putLong("longkey", 343434343434343l);
#4 Apply the changes
Then from the Editor instance we will simply call the apply() method to save the changes.
editor.apply();
Getting Values Back from SharedPreferences
Reading values back is very easy. We have only 2 steps.
Get SharedPreferences
Get Values
#1 Get SharedPreferences
This step is same as we did above.
(adsbygoogle = window.adsbygoogle || []).push();
#2 Get Values
To get the values we have method getDataType() i.e. getString(), getBoolean() etc.
sp.getString("stringkey", "default value"); sp.getBoolean("boolkey", false); sp.getFloat("floatkey", 0.0f); sp.getLong("longkey", 0l);
While reading the values with these methods we pass second parameter as the default value. The default value is returned when we don’t have an already saved value for the specified key.
Modifying Values
Values are overwritten when we save it again. So to modify a value, simply save it again.
Deleting Values
Here we can do two things.
Delete a specific value
Delete everything
#1 Deleting a specific value
From the editor instance we will call remove() method by passing the key that is to be removed from SharedPreferences.
//removing value editor.remove("keytoberemoved"); //commiting the changes editor.apply();
#2 Deleting Everything
Simply call the method clear() and then apply() from the editor, and it will clear everything.
editor.clear(); editor.apply();
Android SharedPreferences Example
Now let’s try everything that we learned so far, in the Android Studio Project.
Creating a Project
Create a new Project. I have created a project named, SharedPrefExample.
Creating User Interface
Now we will create a very simple User Interface.
Android SharedPreferences Example
As you can see, we have an EditText to take value that is to be saved in the SharedPreferences. Below the EditText we also have a TextView (not visible as it has no text now) to display the value already saved. Then we have a Button to save value after entering value in the EditText.
To create the above given UI, you can use the following xml code.
<?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" android:padding="16dp" tools:context="net.simplifiedcoding.sharedprefexample.MainActivity"> <EditText android:id="@+id/editTextName" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Enter your name" /> <TextView android:id="@+id/textView" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/editTextName" android:textAppearance="@style/Base.TextAppearance.AppCompat.Large" /> <Button android:id="@+id/buttonSave" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/textView" android:text="Save" /> </RelativeLayout>
Saving and Reading Values
Write the following code inside MainActivity.java.
package net.simplifiedcoding.sharedprefexample; import android.content.SharedPreferences; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.TextView; public class MainActivity extends AppCompatActivity private static final String SHARED_PREF_NAME = "mysharedpref"; private static final String KEY_NAME = "keyname"; EditText editText; TextView textView; @Override protected void onCreate(Bundle savedInstanceState) super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); editText = findViewById(R.id.editTextName); textView = findViewById(R.id.textView); findViewById(R.id.buttonSave).setOnClickListener(new View.OnClickListener() @Override public void onClick(View view) saveName(); displayName(); ); private void saveName() String name = editText.getText().toString(); if (name.isEmpty()) editText.setError("Name required"); editText.requestFocus(); return; SharedPreferences sp = getSharedPreferences(SHARED_PREF_NAME, MODE_PRIVATE); SharedPreferences.Editor editor = sp.edit(); editor.putString(KEY_NAME, name); editor.apply(); editText.setText(""); private void displayName() SharedPreferences sp = getSharedPreferences(SHARED_PREF_NAME, MODE_PRIVATE); String name = sp.getString(KEY_NAME, null); if (name != null) textView.setText("Welcome " + name);
Now you can try running the application.
Android SharedPreferences Example
You see it is working fine.
So that’s all for this Android SharedPreferences Example. If you are facing any troubles doing it, then let me know in the comment section. And if you found it helpful then help us by SHARING this post. Thank You 🙂















