Skip to content

Instantly share code, notes, and snippets.

@erfanegtfi
Created June 29, 2018 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save erfanegtfi/26f1d0b6845251b38886987b45f13a29 to your computer and use it in GitHub Desktop.
Save erfanegtfi/26f1d0b6845251b38886987b45f13a29 to your computer and use it in GitHub Desktop.
package ir.gushtomorghebaradaran.Utils;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import com.google.gson.Gson;
public class Prefs<T> {
private static SharedPreferences getPreferences(Context context) {
return PreferenceManager.getDefaultSharedPreferences(context);
}
private static SharedPreferences.Editor getPreferencesEditor(Context context) {
return getPreferences(context).edit();
}
public static String getPreferenceValue(Context context, String key, String defValue) {
return getPreferences(context).getString(key, defValue);
}
public static int getPreferenceValue(Context context, String key, int defValue) {
return getPreferences(context).getInt(key, defValue);
}
public static boolean getPreferenceValue(Context context, String key, boolean defValue) {
return getPreferences(context).getBoolean(key, defValue);
}
public static void setPreferenceValue(Context context, String key, String prefsValue) {
getPreferencesEditor(context).putString(key, prefsValue).apply();
}
public static void setPreferenceValue(Context context, String key, int prefsValue) {
getPreferencesEditor(context).putInt(key, prefsValue).apply();
}
public static void setPreferenceValue(Context context, String key, boolean prefsValue) {
getPreferencesEditor(context).putBoolean(key, prefsValue).apply();
}
public static boolean containsPreferenceKey(Context context, String key) {
return getPreferences(context).contains(key);
}
public static void removePreferenceValue(Context context, String key) {
getPreferencesEditor(context).remove(key).apply();
}
public static <T> T getObject(Context context, String key, Class<T> generic) {
Gson gson = new Gson();
String json = getPreferences(context).getString(key, "");
return gson.fromJson(json, generic);
}
public static <T> T putObject(Context context, String key, T value) {
Gson gson = new Gson();
String json = gson.toJson(value);
getPreferencesEditor(context).putString(key, json).apply();
return value;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment