SharedPreference in Android

SharedPreferences in Android to allow us to store primitive data in the form of key value pair . SharedPreferences data will be lost if one of the following conditions are matched .
1. Once you uninstall the App .
2. Once you clear data from the App(Through settings).


            // declaring the pref name
public static final String PREF_NAME = "DEMO";
            // declaring the key name of SharedPreferences
public static final String PREF_USER_ID = "USER_ID";


SharedPreferences sharePref;
Editor editor;

1. Store data in SharedPreferences

public void saveUserId(Context context, String id) {
  
    sharePref = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
    editor = sharePref.edit();

    editor.putString(PREF_USER_ID, id);
    editor.commit();
}

2. Retrieve data from SharedPreferences

public String getUserId(Context context) {
        String text;
    sharePref = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
    text = sharePref.getString(PREF_USER_ID, null);
    return text;
}

3. Remove All values from SharedPreferences

public void clearPrefData(Context context) {

    sharePref = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
    editor = sharePref.edit();

    editor.clear();
    editor.commit();
}

4. Remove Specific values from SharedPreferences

public void removeUserId(Context context) {

    sharePref = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
    editor = sharePref.edit();

    editor.remove(PREF_USER_ID);
    editor.commit();
}


Find Us : 
        Facebook : @apnaandroid
        Google+   : Apna Java
        Youtube : Android & Java Tutorial

Comments

Popular posts from this blog

Custom Calendar in android

Disable/Hide Year from DatePickerDialog in android

Coordinator Layout in Android