Skip to content

fefong/android_sharedpreferences

Repository files navigation

Android/Java: Shared Preferences

Example Android/Java: Shared Preferences;

Constants

Declare variables constants.

⚠️ It is recommended to use constant variables to declare as KEYs.

private SharedPreferences sharedPreferences;
private SharedPreferences.Editor editorSharedPreferences;
private String KEY="KEY";

Initialize the variables.

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO

    sharedPreferences = getSharedPreferences(KEY, Context.MODE_PRIVATE);

    editorSharedPreferences = sharedPreferences.edit();
}

Save Shared Preference

editorSharedPreferences.putString(KEY,"TEXT");

editorSharedPreferences.apply();

Get Shared Preference

if (sharedPreferences.contains(KEY)) {
    String text = sharedPreferences.getString(KEY, "");
    // TODO
}

Delete Shared Preference

editorSharedPreferences.remove(KEY);
editorSharedPreferences.commit();

Screenshots

Image Shared Preferences

See implementation: code

Some links for more in depth learning