Shared Preferences to handle Sessions in android
by Sasikumar[ Edit ] 2013-10-10 12:08:37
To handle sessions in android we can use SharedPreferences:
Step 1:Create an object for SharedPreferences as follows
SharedPreferences preferences = getSharedPreferences(PREFS_NAME,Context.MODE_PRIVATE);
Step 2:Create an Editor Object to edit the SharedPreferences variables
SharedPreferences.Editor editor = preferences.edit();
Step 3:Using editor store the values in SharedPreferences variables as follows
editor.putBoolean("key_name", true); // To store a Boolean Value
editor.putString("key_name", "string value"); // To store a String Value
editor.putInt("key_name", "int value"); // To store a Integer Value
editor.putFloat("key_name", "float value"); // To store a Float Value
Step 3:The following statement must be given inorder to store the changes
editor.commit();
Step 4:In order to retrieve a data use the following
preferences.getBoolean("key_name", null); // To get a Boolean Value
preferences.getString("key_name", null); // To get a String Value
preferences.getInt("key_name", null); // To get a Integer Value
preferences.getFloat("key_name", null); // To get a Float Value
Step 6:In order to clear a data use the following options
Clear individual key_name
editor.remove("key_name"); // will delete the particular key_name
editor.commit(); // store the changes
Clear all key_names
editor.clear(); //clears all key_names in the SharedPreferences with the particular editor
editor.commit(); // store the changes