Skip to content

Instantly share code, notes, and snippets.

@theyann
Created December 11, 2015 20:47
Show Gist options
  • Save theyann/84261142b88dfb0ca57b to your computer and use it in GitHub Desktop.
Save theyann/84261142b88dfb0ca57b to your computer and use it in GitHub Desktop.
PrefUtils is a base class intended to simplify and clarify the code relative to dealing with SharedPreferences. It is very simple and it is meant to be.
package X.Y.Z;
import android.content.SharedPreferences;
/**
* Created by ylemin on 21/11/15.
*
* This class is a bunch of recurring methods used when dealing with SharedPreferences.
* It is intended to be a base class which receives the SharedPreferences instance from the child class.
* There should only be one instance of SharedPreferences per app.
*/
public abstract class PrefUtils {
/**
* Abstract Methods
*/
public abstract SharedPreferences prefs();
/**
* Public Methods
*/
public void clear() {
prefs().edit().clear().apply();
}
public boolean has(String key) {
return prefs().contains(key);
}
public void set(String key, String value) {
SharedPreferences.Editor editor = prefs().edit();
editor.putString(key, value);
editor.apply();
}
public String getString(String key) {
return prefs().getString(key, null);
}
public void set(String key, Boolean value) {
SharedPreferences.Editor editor = prefs().edit();
editor.putBoolean(key, value);
editor.apply();
}
public Boolean getBoolean(String key) {
return prefs().getBoolean(key, false);
}
public void reset(String key) {
SharedPreferences.Editor editor = prefs().edit();
editor.remove(key);
editor.apply();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment