Created
June 29, 2018 13:56
-
-
Save erfanegtfi/26f1d0b6845251b38886987b45f13a29 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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