Skip to content

Instantly share code, notes, and snippets.

@khangaldi
Created January 22, 2017 12:17
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 khangaldi/7c1128f6ff5c814496c83f65d4753749 to your computer and use it in GitHub Desktop.
Save khangaldi/7c1128f6ff5c814496c83f65d4753749 to your computer and use it in GitHub Desktop.
SharedPreference the new way
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
public class KPref {
enum KDataType {
String(1),
Boolean(2),
Float(3),
Integer(4),
Long(5);
private int value;
private KDataType(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
public <T extends String> void saveItem(T key, Object value, Context context) {
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(context)
.edit();
if (value instanceof String) {
editor.putString(key, (String) value);
editor.putInt(key+"_", KDataType.String.getValue());
}
if (value instanceof Boolean) {
editor.putBoolean(key, (Boolean) value);
editor.putInt(key+"_", KDataType.Boolean.getValue());
}
if (value instanceof Float) {
editor.putFloat(key, (Float) value);
editor.putInt(key+"_", KDataType.Float.getValue());
}
if (value instanceof Integer) {
editor.putInt(key, (Integer) value);
editor.putInt(key+"_", KDataType.Integer.getValue());
}
if (value instanceof Long) {
editor.putLong(key, (Long) value);
editor.putInt(key+"_", KDataType.Long.getValue());
}
editor.apply();
}
public <T extends String> Object getItem(T key, Context context) {
Integer valueType = PreferenceManager.getDefaultSharedPreferences(context).getInt(key+"_", 0);
if (KDataType.Boolean.getValue() == valueType) {
return PreferenceManager.getDefaultSharedPreferences(context).getBoolean(key, false);
}
if (KDataType.Integer.getValue() == valueType) {
return PreferenceManager.getDefaultSharedPreferences(context).getInt(key, 0);
}
if (KDataType.Float.getValue() == valueType) {
return PreferenceManager.getDefaultSharedPreferences(context).getFloat(key, 0);
}
if (KDataType.Long.getValue() == valueType) {
return PreferenceManager.getDefaultSharedPreferences(context).getLong(key, 0);
}
if (KDataType.String.getValue() == valueType) {
return PreferenceManager.getDefaultSharedPreferences(context).getString(key, "");
}
IllegalStateException exception = new IllegalStateException("Variable is not recognised");
throw exception;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment