android SharedPreferences封装类 简单 好用的类

在项目中经常会用到SharedPreferences储存一些临时文件,如登录账号.密码 ,ip等 ,有时候想起来就写一个,弄的项目很乱,在此封装好了一个类,代码如下:

public class mySharePreferences {  
    public static final String SERVER_IP = "mServerIP";  
    public static final String SERVER_PORT = "mServerPort";  
    public static final String SERVER_NAME = "mServerName";  
    SharedPreferences sharedPreferences;  
    Editor editor;  
  
    private mySharePreferences() {  
    };  
  
    public static mySharePreferences getIntanse() {  
        return Nested.mV2SharePreferences;  
    }  
  
    static class Nested {  
        private static mySharePreferences mV2SharePreferences = new mySharePreferences();  
    }  
  
    public SharedPreferences.Editor getEditor() {  
        if (editor == null || sharedPreferences == null) {  
            editor = getSharePreferences().edit();  
        }  
        return editor;  
    }  
  
    public SharedPreferences getSharePreferences() {  
        if (sharedPreferences == null) {  
            sharedPreferences = PreferenceManager  
                    .getDefaultSharedPreferences(V2Application.getContext());  
        }  
        return sharedPreferences;  
    }  
  
    public void putStringValue(String key, String value) {  
        getEditor().putString(key, value);  
        getEditor().commit();  
    }  
  
    public String getStringValue(String key, String defaultValue) {  
        return getSharePreferences().getString(key, defaultValue);  
    }  
  
    public void putBooleanValue(String key, boolean value) {  
        getEditor().putBoolean(key, value);  
        getEditor().commit();  
    }  
  
    public boolean getBooleanValue(String key, boolean defaultValue) {  
        return getSharePreferences().getBoolean(key, defaultValue);  
    }  



调用的时候非常方便   如果要储存数据直接调用mySharePreferences.getintanse().putStringValue(string key,string value);

获取数据的时候用mySharePreferences.getintanse().getStringValue(string key,string defaultValue);是不是感觉非常的方便   

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值