How to Use Android SharedPreferences

Some saying about SharedPreferences

SharedPreferences is an API from Android SDK to store and retrieve application preferences. SharedPreferences are simply sets of data values that stored persistently. Persistently which mean data you stored in the SharedPreferences are still exist even if you stop the application or turn off the device. SharedPreferences available at the Activity level or shared across all Activity in application package.

When I use it ?

Whenever your app requires data to be stored persistenly, even you close the application or turn off the device, or you need to share your data across all Activity in application package. For example, your application might want to store the user’s name, or you want to store game current score, current level, etc

When the app use Single Sign On Facebook it use SharedPreferences to store access_token, access_expire, etc. After you complete log in with facebook in the app, it store some data including access_token and access_expire to the app preferences. And when you reopen, it will check the access_token and access_expire values, if access_token return null, the session is no more valid and you have to login with facebook again.

Ok, enough theory i’ll show you how to create application-level SharedPreferences

let’s get a cup of coffee…

Step 1 : Specify data and create specific class for handle SharedPreferences

In this step you will  specify data that you want to store it in SharedPreferences. For example, i will store user’s name and user’s id after a sucessfull login.

Create specific class for handling SharedPreferences.

package uin.luthfihariz.simplebankclient;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

public class AppPrefs {
 private static final String USER_PREFS = "USER_PREFS";
 private SharedPreferences appSharedPrefs;
 private SharedPreferences.Editor prefsEditor;
 private String user_name = "user_name_prefs";
 private String user_id = "user_id_prefs";

public AppPrefs(Context context){
 this.appSharedPrefs = context.getSharedPreferences(USER_PREFS, Activity.MODE_PRIVATE);
 this.prefsEditor = appSharedPrefs.edit();
 }
public int getUser_id() {
 return appSharedPrefs.getInt(user_id, 0);
 }

public void setUser_id(int _user_id) {
 prefsEditor.putInt(user_id, _user_id).commit();
}
public String getUser_name() {
 return appSharedPrefs.getString(user_name, "unkown");
 }

 public void setUser_name( String _user_name) {
 prefsEditor.putString(user_name, _user_name).commit();
 }

}

Actually you don’t have to create one specific class for handling SharedPreferences. But i prefer this way because it ease, moreover if you will store a lot of data variable. Then how those codes work ?

These preferences are retrieve using getSharedPreferences method from the application Context class. And you may want to declare your preference set names so that you can easily store and retrieve data preferences from any Activity within your application. Edit() method from SharedPreferences class are used for store or update data in the preferences.

private static final String USER_PREFS = "USER_PREFS";
public AppPrefs(Context context){
 this.appSharedPrefs = context.getSharedPreferences(USER_PREFS, Activity.MODE_PRIVATE);
 this.prefsEditor = appSharedPrefs.edit();
 }

The following data types are supported by the SharedPreferences class:

  • Boolean, use putBoolean() method to store and getBoolean() to retrieve
  • Float, use putFloat() method to store and getFloat() to retrieve
  • Integer, use putInt() method to store and getInt() to retrieve
  • Long, use putLong() method to store and getLong() to retrieve
  • String, use putString() method to store and getString to retrieve

Step 2 : Store, Retrieve or Update data in SharedPreferences

To store or update data you can initiate AppPrefs class by passing application context and call setter method. Here is the snippet code for storing data.

String name = "Luthfi Hariz";
int id = "5";
Context context = getApplicationContext();
AppPrefs appPrefs = new AppPrefs(context);
appPrefs.setUser_name(name);
appPrefs.setUser_id(id);

And for retrieve data, as simple as this.

Context context = getApplicationContext();
 AppPrefs appPrefs = new AppPrefs(context);
 int id = appPrefs.getUser_id();
 String name = appPrefs.getUser_fname();

Conclusion

SharedPreferences can be easily use to store application data persistently, you also available to store data accross all activities in the application package. SharedPreferences are stored as key-value pairs, the following data types supported are integer, float, double, string and boolean.

This post is inspired by the tutorial from mobile tutsplus

Please introduce my first Android Application, Sharee (Sharia Economics Education) now on Play Store.

and here is My post (in Bahasa) about Sharee.

Advertisements

2 thoughts on “How to Use Android SharedPreferences

  1. woke dah mantep abis skripsi w selese w coba. . . ^^

  2. ahmed says:

    Jazak allah khair,,, my brother 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: