自定义SharedPreferences的封装

来源:互联网 发布:android图片压缩算法 编辑:程序博客网 时间:2024/04/28 19:07

SpUtil类是对android.content.SharedPreferences的封装,简化了对其的使用。代码如下:

public class SpUtil {    private static final String NAME="EY"; //保存文件的名称    private static SpUtil instance;    public static SpUtil getInstance(){        if(instance==null){            instance=new SpUtil();        }        return instance;    }    private SharedPreferences getSharePerference(Context context){        return context.getSharedPreferences(NAME, Context.MODE_PRIVATE);    }    public String getString(Context context,String key){        return SpUtil.getInstance().getSharePerference(context).getString(key, null);    }    public void setString(Context context,String key,String value){        Editor editor=SpUtil.getInstance().getSharePerference(context).edit();        editor.putString(key, value);        editor.commit();    }    public boolean getBoolean(Context context,String key){        return SpUtil.getInstance().getSharePerference(context).getBoolean(key, false);    }    public void setBoolean(Context context,String key,boolean value){        Editor editor=SpUtil.getInstance().getSharePerference(context).edit();        editor.putBoolean(key, value);        editor.commit();    }    public int getInt(Context context,String key){        return SpUtil.getInstance().getSharePerference(context).getInt(key, 0);    }    public void setInt(Context context,String key,int value){        Editor editor=SpUtil.getInstance().getSharePerference(context).edit();        editor.putInt(key, value);        editor.commit();    }    public Set<String> getStringSet(Context context,String key){        return SpUtil.getInstance().getSharePerference(context).getStringSet(key, null);    }    public void setStringSet(Context context,String key,Set<String> value){        Editor editor=SpUtil.getInstance().getSharePerference(context).edit();        editor.putStringSet(key, value);        editor.commit();    }}

注:使用时直接调用即可,例如String类型,调用代码如下:

SpUtil.getInstance().setString(this, "hello", "hello world");String str=SpUtil.getInstance().getString(this, "hello");
0 0
原创粉丝点击