In android, Shared Preferences are used to save and retrieve the primitive data types (integer, float, boolean, string, long) data in the form of key-value pairs from a file within an apps file structure.
Generally, the Shared Preferences object will point to a file that contains key-value pairs and provides a simple read and write methods to save and retrieve the key-value pairs from a file.
The Shared Preferences file is managed by an android framework and it can be accessed anywhere within the app to read or write data into the file, but it’s not possible to access the file from any other app so it’s secured.
The Shared Preferences are useful to store the small collection of key-values such as user’s login information, app preferences related to users, etc. to maintain the state of the app, next time when they login again to the app.
In android, we can save the preferences data either in single or multiple files based on our requirements.
In case if we use a single file to save the preferences, then we need to use getPreferences() method to get the values from Shared Preferences file and for multiple files, we need to call a getSharedPreferences() method and pass a file name as a parameter.
Method | Description |
---|---|
getPreferences() | This method is for activity level preferences and each activity will have its own preference file and by default, this method retrieves a default shared preference file that belongs to the activity. |
getSharedPreferences() | This method is useful to get the values from multiple shared preference files by passing the name as a parameter to identify the file. We can call this from any Context in our app. |
The following are the different ways to initialize the Shared Preferences in our application.
If we are using single shared preference file for our activity, then we need to initialize the SharedPreferences object by using getPreferences() method like as shown below.
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
In case, if we are using multiple shared preference files, then we need to initialize the SharedPreferences object by using the getSharedPreferences() method like as shown below.
Here, the name “filename1” is the preference file, which wants to read the values based on our requirements and the context mode MODE_PRIVATE, will make sure that the file can be accessed only within our application.
To store data in a shared preference file, we need an editor to edit and save the changes in the SharedPreferences object. Following is the code snippet to store the data in shared preference file using an editor.
If you observe above code snippet, we created a SharedPreferences.Editor by calling the edit() method of SharedPreferences object. We added a primitive data type values such as integer, float, long, string and Boolean by passing the keys and values to the methods putInt(), putString(), etc. based on our requirements. After that, to save all the changes we are calling commit() method.
To read or retrieve values from the Shared Preferences file, we need to call methods such as getInt(), getString(), etc. by providing the key for the value which we want to get like as shown below.
If you observe above code snippet, we are getting the values from shared preferences using a methods such as getInt(), getFloat(), etc. by providing the key for the value which we want to get.
To delete values from the Shared Preferences file, we need to call remove() method by providing the key for the value which we want to delete like as shown below.
If you observe above code snippet, we are deleting the values from shared preferences using a method called remove() by providing the key for the value which we want to delete and committing the changes to shared preferences file using commit() method.
We can clear all the data from Shared Preferences file using a clear() method like as shown below.
If you observe above code snippet, we are clearing all the values from shared preferences using a method called clear() and committing the changes to shared preferences file using commit() method.
Now we will see how to store and retrieve primitive data type key-value pairs in shared preferences file using SharedPreferences object in android application with examples.
Following is the example of storing and retrieving the primitive data type values from shared preferences file using SharedPreferences.
Create a new android application using android studio and give names as SharedPreferencesExample. In case if you are not aware of creating an app in android studio check this article Android Hello World App.
Once we create an application, open activity_main.xml file from \res\layout folder path and write the code like as shown below.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/fstTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:layout_marginTop="150dp"
android:text="UserName" />
<EditText
android:id="@+id/txtName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:ems="10"/>
<TextView
android:id="@+id/secTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Password"
android:layout_marginLeft="100dp" />
<EditText
android:id="@+id/txtPwd"
android:inputType="textPassword"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:ems="10" />
<Button
android:id="@+id/btnLogin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:text="Login" />
</LinearLayout>
Now we will create another layout resource file details.xml in \res\layout path to get the first activity (activity_main.xml) details in second activity file for that right click on your layout folder à Go to New à select Layout Resource File and give name as details.xml.
Once we create a new layout resource file details.xml, open it and write the code like as shown below
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/resultView"
android:layout_gravity="center"
android:layout_marginTop="170dp"
android:textSize="20dp"/>
<Button
android:id="@+id/btnLogOut"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="20dp"
android:text="Log Out" />
</LinearLayout>
Now open your main activity file MainActivity.java from \java\com.tutlane.sharedpreferencesexample path and write the code like as shown below
package com.tutlane.sharedpreferencesexample;
import android.content.Intent;
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.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
EditText uname, pwd;
Button loginBtn;
SharedPreferences pref;
Intent intent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
uname = (EditText)findViewById(R.id.txtName);
pwd = (EditText)findViewById(R.id.txtPwd);
loginBtn = (Button)findViewById(R.id.btnLogin);
pref = getSharedPreferences("user_details",MODE_PRIVATE);
intent = new Intent(MainActivity.this,DetailsActivity.class);
if(pref.contains("username") && pref.contains("password")){
startActivity(intent);
}
loginBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String username = uname.getText().toString();
String password = pwd.getText().toString();
if(username.equals("suresh") && password.equals("dasari")){
SharedPreferences.Editor editor = pref.edit();
editor.putString("username",username);
editor.putString("password",password);
editor.commit();
Toast.makeText(getApplicationContext(), "Login Successful",Toast.LENGTH_SHORT).show();
startActivity(intent);
}
else
{
Toast.makeText(getApplicationContext(),"Credentials are not valid",Toast.LENGTH_SHORT).show();
}
}
});
}
}
If you observe above code, we are checking whether the entered username and password details matching or not based on that we are saving the details in shared preferences file and redirecting the user to another activity.
Now we will create another activity file DetailsActivity.java in \java\com.tutlane.sharedpreferencesexample path to show the details from shared preference file for that right-click on your application folder à Go to New à select Java Class and give name as DetailsActivity.java.
Once we create a new activity file DetailsActivity.java, open it and write the code like as shown below
package com.tutlane.sharedpreferencesexample;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
/**
* Created by tutlane on 03-01-2018.
*/
public class DetailsActivity extends AppCompatActivity {
SharedPreferences prf;
Intent intent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.details);
TextView result = (TextView)findViewById(R.id.resultView);
Button btnLogOut = (Button)findViewById(R.id.btnLogOut);
prf = getSharedPreferences("user_details",MODE_PRIVATE);
intent = new Intent(DetailsActivity.this,MainActivity.class);
result.setText("Hello, "+prf.getString("username",null));
btnLogOut.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SharedPreferences.Editor editor = prf.edit();
editor.clear();
editor.commit();
startActivity(intent);
}
});
}
}
Now we need to add this newly created activity in AndroidManifest.xml file in like as shown below.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tutlane.sharedpreferencesexample">
<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">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".DetailsActivity" android:label="Shared Preferences - Details"></activity>
</application>
</manifest>
If you observe above example, we are checking whether the entered user details matching or not based on that we are saving the user details in shared preferences file and redirecting the user to another activity file (DetailsActivity.java) to show the users details and added all the activities in AndroidManifest.xml file.
When we run above example in android emulator we will get a result like as shown below
If you observe above result, the entered username and password matches then we are redirecting user to another activity file to show the user details from shared preferences file. After that, if we click on the Logout button, it will clear all the values in the shared preferences file and it will redirect user to login page.
This is how we can use Shared Preferences in android applications to store and retrieve key-value pair values based on our requirements.