码迷,mamicode.com
首页 > 其他好文 > 详细

5:SharedPreferences类封装

时间:2017-11-11 11:19:44      阅读:121      评论:0      收藏:0      [点我收藏+]

标签:value   shared   val   str   void   string   log   utils   share   

1:SharedPreferencesUtils.java

import android.content.Context;
import android.content.SharedPreferences;

public class SharedPreferencesUtils {

    public static final String SP_NAME = "config";
    private static SharedPreferences sp;

    /**
     * 保存字符串
     * 
     * @param context
     * @param key
     * @param value
     */
    public static void saveString(Context context, String key, String value) {
        if (sp == null)
            sp = context.getSharedPreferences(SP_NAME, 0);
        sp.edit().putString(key, value).commit();
    }
    

    /**
     * 保存布尔
     * 
     * @param context
     * @param key
     * @param value
     */
    public static void saveBoolean(Context context, String key, boolean value) {
        if (sp == null)
            sp = context.getSharedPreferences(SP_NAME, 0);
        sp.edit().putBoolean(key, value).commit();
    }

    public static void saveInt(Context context, String key, int value) {
        if (sp == null)
            sp = context.getSharedPreferences(SP_NAME, 0);
        sp.edit().putInt(key, value).commit();
    }
    
    public static int getInt(Context context, String key, int defValue) {
        if (sp == null)
            sp = context.getSharedPreferences(SP_NAME, 0);
        return sp.getInt(key, defValue);
    }
    public static void saveFloat(Context context, String key, float value) {
        if (sp == null)
            sp = context.getSharedPreferences(SP_NAME, 0);
        sp.edit().putFloat(key, value).commit();
    }
    public static float getFloat(Context context, String key, float defValue) {
        if (sp == null)
            sp = context.getSharedPreferences(SP_NAME, 0);
        return sp.getFloat(key, defValue);
    }

    /**
     * 返回字符串
     * 
     * @param context
     *            上下文
     * @param key
     *            key
     * @param defValue
     *            默认值
     * @return
     */
    public static String getString(Context context, String key, String defValue) {
        if (sp == null)
            sp = context.getSharedPreferences(SP_NAME, 0);
        return sp.getString(key, defValue);
    }

    public static boolean getBoolean(Context context, String key,
            boolean defValue) {
        if (sp == null)
            sp = context.getSharedPreferences(SP_NAME, 0);
        return sp.getBoolean(key, defValue);
    }
}

 

5:SharedPreferences类封装

标签:value   shared   val   str   void   string   log   utils   share   

原文地址:http://www.cnblogs.com/wnpp/p/7817358.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!