public class SpInstance {
public static final String SP_NAME = "my_sp_config";
private Context applicationContext = null;
private SharedPreferences sharedPreferences = null;
public static final int ERROR_CODE = -1;
private static SpInstance instance = null;
private static final Object INSTANCE_LOCK = new Object();
public static SpInstance getInstance() {
if (instance == null) {
synchronized (INSTANCE_LOCK) {
if (instance == null) {
instance = new SpInstance();
}
}
}
return instance;
}
public void init(Context context) {
this.applicationContext = context.getApplicationContext();
}
private SharedPreferences getSp() {
if (sharedPreferences == null) {
sharedPreferences = applicationContext.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
}
return sharedPreferences;
}
private SharedPreferences.Editor getEdit() {
return getSp().edit();
}
public <T> void put(String key, T value) {
if (getEdit() != null) {
if (value instanceof Boolean) {
getEdit().putBoolean(key, (Boolean) value).commit();
} else if (value instanceof String) {
getEdit().putString(key, (String) value).commit();
} else if (value instanceof Integer) {
getEdit().putInt(key, (Integer) value).commit();
} else if (value instanceof Float) {
getEdit().putFloat(key, (Float) value).commit();
} else if (value instanceof Long) {
getEdit().putLong(key, (Long) value).commit();
}
}
}
public boolean getBoolean(String key, boolean defaultValue) {
if (getSp() != null) {
return getSp().getBoolean(key, defaultValue);
}
return false;
}
public String getString(String key, String defaultValue) {
if (getSp() != null) {
return getSp().getString(key, defaultValue);
}
return "";
}
public int getInt(String key, int defaultValue) {
if (getSp() != null) {
return getSp().getInt(key, defaultValue);
}
return ERROR_CODE;
}
public float getFloat(String key, float defaultValue) {
if (getSp() != null) {
return getSp().getFloat(key, defaultValue);
}
return ERROR_CODE;
}
public long getLong(String key, long defaultValue) {
if (getSp() != null) {
return getSp().getLong(key, defaultValue);
}
return ERROR_CODE;
}
}