SharedPreferences封装
- 存
- 取
- 封装类
存
首先初始化
private SP sp;
sp = new SP( context );
存入数据
第一个参数为上下文,第二个参数为key,第三个参数为要存入的数据Value
sp.PutData( context,"AccessToken",AccessToken );
取
初始化
private SP sp;
sp = new SP( context );
取出数据
第一个参数为上下文,第二个参数为存入数据时定义的名称,第三个数据为取出数据的默认类型(这个参数很关键,再封装类转换类型时尤为重要)
AccessToken = (String) sp.GetData( context,"AccessToken","" );
封装类
public class SP {
private static SP spInstant;
private String defaultModelName;
public SP(){
}
public SP (Context context){
if (spInstant == null){
spInstant = new SP( );
spInstant.defaultModelName = context.getResources().getString( R.string.DefaultModelName );
}
}
public void PutData(Context context,String key,Object value){
PutData( context,defaultModelName,key,value );
}
private void PutData(Context context,String defaultModelName ,String key,Object value){
SharedPreferences preferences = context.getSharedPreferences( defaultModelName,Context.MODE_PRIVATE );
SharedPreferences.Editor editor = preferences.edit();
if (value instanceof Boolean){
editor.putBoolean( key,(Boolean) value );
}else if (value instanceof Integer){
editor.putInt( key,(Integer)value );
}else if (value instanceof Float){
editor.putFloat( key,(Float)value );
}else if (value instanceof Long){
editor.putLong( key,(Long)value );
}else if (value instanceof String){
editor.putString( key,(String)value );
}else{
return;
}
editor.apply();
}
public Object GetData(Context context,String key,Object defaultValue){
return GetData( context,defaultModelName,key,defaultValue);
}
private Object GetData(Context context,String defaultModelName,String key,Object defaultValue){
SharedPreferences preferences = context.getSharedPreferences( defaultModelName,Context.MODE_PRIVATE );
if (defaultValue instanceof Boolean){
return preferences.getBoolean( key,(Boolean) defaultValue );
}else if (defaultValue instanceof Integer){
return preferences.getInt( key,(Integer) defaultValue );
}else if (defaultValue instanceof Float){
return preferences.getFloat( key,(Float) defaultValue );
}else if (defaultValue instanceof Long){
return preferences.getLong( key,(Long) defaultValue );
}else if (defaultValue instanceof String){
return preferences.getString( key,(String) defaultValue );
}else{
return null;
}
}
}