Android SharedPreferences工具类

/**
 * Created by Sunday on 2016/3/17.
 */
public class SPUtil {

    public static final String SP_NAME = "sunday_sp";
    /**
     * 用于文本信息的存储
     */
    SharedPreferences preferences;

    /**
     * 无参构造方法
     */
    public SPUtil() {
    }

    /**
     * 带1个参的构造方法,spName默认
     */
    public SPUtil(Context context) {
        preferences = context.getSharedPreferences(SP_NAME,
                Context.MODE_PRIVATE);
    }

    /**
     * 带2个参的构造方法,自定义spName
     */
    public SPUtil(Context context, String spName) {
        preferences = context.getSharedPreferences(spName, Context.MODE_PRIVATE);
    }

    /**
     * 保存String
     *
     * @param key
     * @param value
     */
    public void save(String key, String value) {
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString(key, value);
        editor.commit();
    }

    /**
     * 保存int
     *
     * @param key
     * @param value
     */
    public void save(String key, int value) {
        SharedPreferences.Editor editor = preferences.edit();
        editor.putInt(key, value);
        editor.commit();
    }

    /**
     * 保存boolean
     *
     * @param key
     * @param value
     */
    public void save(String key, boolean value) {
        SharedPreferences.Editor editor = preferences.edit();
        editor.putBoolean(key, value);
        editor.commit();
    }

    /**
     * 获取String
     *
     * @param key
     * @param defValue
     * @return
     */
    public String getString(String key, String defValue) {
        return preferences.getString(key, defValue);
    }

    /**
     * 获取int
     *
     * @param key
     * @param defValue
     * @return
     */
    public int getInt(String key, int defValue) {
        return preferences.getInt(key, defValue);
    }

    /**
     * 获取boolean
     *
     * @param key
     * @param defValue
     * @return
     */
    public boolean getBoolean(String key, boolean defValue) {
        return preferences.getBoolean(key, defValue);
    }
}

你可能感兴趣的:(android)