Saturday 18 May 2013

Android Shared Preferences

Hi all,

In this post we will learn about how to use shared preferences.
Shard preferences is nothing but simply we can say small Database. Normally we will use one library variable or temporary variable to store the values. If suppose your app gets crash in some pages means your temporary variable will loose their assigned values.

To know more about shared Preferences please gothrough the following link .
http://developer.android.com/reference/android/content/SharedPreferences.html

Step 1: 
To obtain shared preferences, use the following method In your activity:
SharedPreferences prefs = this.getSharedPreferences("Rajesh", Context.MODE_PRIVATE);

Step 2:

To read preferences:

SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(this);
        String text = app_preferences.getString("UserName", "null");

like getString you can have lot of methods like below

for Boolean values
 boolean Ischeck = app_preferences.getBoolean("key", false);

for float values 

   float text1 = app_preferences.getFloat("key", 0f);

for long values :

long text1 = app_preferences.getLong("key", 0l);

for int values:

int text1 = app_preferences.getInt("key", 0);

To edit and save preferences

public static final String PREFS_NAME = "LoginPrefs"; //
By using above line you can create multiple shared preferences file .

SharedPreferences settings = getSharedPreferences(PREFS_NAME,0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("value1", "Rajesh");
editor.commit();

if you want to add all the values in single preferences file use the below lines. 

SharedPreferences app_preferences =
               PreferenceManager.getDefaultSharedPreferences(this);
               SharedPreferences.Editor editor1 = app_preferences.edit();
                  editor1.putString("key", text);
               editor1.putString("key1", text1);

               editor1.commit();

The android sdk's sample directory contains an example of retrieving and stroing shared preferences. Its located in the:

<android-sdk-home>/samples/android-<platformversion>/ApiDemos directory

No comments: