Skip to content

Instantly share code, notes, and snippets.

@swapnildroid
Last active October 12, 2016 01:22
Show Gist options
  • Save swapnildroid/04f88e9f4b4d6e014dbf70de8371bd01 to your computer and use it in GitHub Desktop.
Save swapnildroid/04f88e9f4b4d6e014dbf70de8371bd01 to your computer and use it in GitHub Desktop.
Easy way to add/remove Android preferences.
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
public enum EasyPref {
AString,
ABoolean,
AInt,
;
private static SharedPreferences sp;
/**
Initialize from application class.
*/
public static void init(Application application) {
Context applicationContext = application.getApplicationContext();
sp = applicationContext
.getSharedPreferences(
applicationContext.getPackageName(), Context.MODE_PRIVATE);
}
public void clearAll() {
edit().clear().commit();
}
public void remove() {
edit().remove(name()).commit();
}
public String getString() {
return getString(null);
}
public int getInt() {
return getInt(-1);
}
public boolean getBoolean() {
return getBoolean(false);
}
public String getString(String defValue) {
if (sp == null) return defValue;
return sp.getString(name(), null);
}
public int getInt(int defValue) {
if (sp == null) return defValue;
return sp.getInt(name(), defValue);
}
public boolean getBoolean(boolean defValue) {
if (sp == null) return defValue;
return sp.getBoolean(name(), defValue);
}
public void put(String value) {
if (sp != null)
edit().putString(name(), value).commit();
}
public void put(int value) {
if (sp != null)
edit().putInt(name(), value).commit();
}
public void put(boolean value) {
if (sp != null)
edit().putBoolean(name(), value).commit();
}
private SharedPreferences.Editor edit() {
return sp.edit();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment