Skip to content

Instantly share code, notes, and snippets.

@andhikayuana
Created September 7, 2017 05:17
Show Gist options
  • Save andhikayuana/e69b2b27d08553d87af312fb98b6e5c7 to your computer and use it in GitHub Desktop.
Save andhikayuana/e69b2b27d08553d87af312fb98b6e5c7 to your computer and use it in GitHub Desktop.
Shared Preferences Android Utility
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
/**
* @author yuana <[email protected]>
* @since 12/27/16
*/
public class SharedPrefUtil {
private static SharedPreferences getPref() {
Context context = /*your context here*/;
return PreferenceManager.getDefaultSharedPreferences(context);
}
public static void saveString(String key, String value) {
getPref().edit().putString(key, value).apply();
}
public static String getString(String key) {
return getPref().getString(key, null);
}
public static void saveInt(String key, int value) {
getPref().edit().putInt(key, value).apply();
}
public static int getInt(String key) {
return getPref().getInt(key, 0);
}
public static void saveBoolean(String key, boolean value) {
getPref().edit().putBoolean(key, value).apply();
}
public static boolean getBoolean(String key) {
return getPref().getBoolean(key, false);
}
public static void saveLong(String key, Long value) {
getPref().edit().putLong(key, value).apply();
}
public static Long getLong(String key) {
return getPref().getLong(key, 0);
}
public static void saveFloat(String key, float value) {
getPref().edit().putFloat(key, value).apply();
}
public static float getFloat(String key) {
return getPref().getFloat(key, 0);
}
public static void remove(String key) {
getPref().edit().remove(key).apply();
}
public static SharedPreferences.Editor getEditor() {
return getPref().edit();
}
}
@andhikayuana
Copy link
Author

You can use like this

SharedPrefUtil.saveBoolean("KEY_IS_LOGIN", true);

SharedPrefUtil.getBoolean("KEY_IS_LOGIN");

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment