WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

Shared Preference Android


Shared Preference in Android are used to save data based on key-value pair.


Shared Preference can be used to save primitive data type: string, long, int, float and Boolean.

Type of shared Preference


    Context.MODE_PRIVATE – default value (Not accessible outside of your application)
    Context.MODE_WORLD_READABLE – readable to other apps
    Context.MODE_WORLD_WRITEABLE – read/write to other apps


MODE_PRIVATE This mode is active state on default.This mode is generally used . Context.MODE_WORLD_READABLE outside application can easily read data of your app. This mode is very rarely used in App. MODE_WORLD_WRITEABLE In this mode have two properties such as read and write.
Note
if your application package name is com.welookups.weapp then preference could be com.welookups.weapp.User where com.welookups.weapp.User is the name of preference file.

Remove Data Or Clear All Data

remove(String key) in SharedPreferences.Editor to remove a particular key based data from preference file. clear() available in SharedPreferences.Editor
public static final String PREFS_GAME ="com.awelookups.weapp.GamePlay";
public static final String GAME_SCORE= "GameScore";

//======== Code to save data when edit===================

SharedPreferences sp = getSharedPreferences(PREFS_GAME ,Context.MODE_PRIVATE);
sp.edit().putInt(GAME_SCORE,400).commit();

//========= Code to get saved/ retrieve data ==============

SharedPreferences sp = getSharedPreferences(PREFS_GAME ,Context.MODE_PRIVATE);
int sc  = sp.getInt(GAME_SCORE,-5);
Log.d("welookups","achieved score  is "+ sc);

SharedPreferences object by calling getPreferences (int mode) or getSharedPreferences (String name,int mode).