自己写了个SP辅助类
虽然写的有点啰嗦,也是自己的成果。如下:
package com.yqy.yqy_testsputil;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
/**
* SP辅助类
* @author YQY
*
*
*/
@SuppressLint("CommitPrefEdits")
public class SPUtil {
private static SharedPreferences mSP;
private static String spName = "yqy_testsputil";
/**
* put
* @param context 环境
* @param name 键
* @param object 值
*/
public static void put(Context context,String name,Object object){
mSP = context.getSharedPreferences(spName, Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = mSP.edit();
if(object instanceof String){
editor.putString(name,(String) object);
}else if(object instanceof Integer){
editor.putInt(name, (Integer) object);
}else if(object instanceof Long){
editor.putLong(name, (Long) object);
}else if(object instanceof Float){
editor.putFloat(name, (Float) object);
}else if(object instanceof Boolean){
editor.putBoolean(name, (Boolean) object);
}
editor.commit();
}
public static void set(Context context, String what, String value) {
SharedPreferences sharedPreferences = context.getSharedPreferences(spName, 0);
sharedPreferences.edit().putString(what, value).commit();
}
public static String getString(Context context,String name){
mSP = context.getSharedPreferences(spName, Activity.MODE_PRIVATE);
return mSP.getString(name, "");
}
public static int getInt(Context context,String name){
mSP = context.getSharedPreferences(spName, Activity.MODE_PRIVATE);
return mSP.getInt(name, 0);
}
public static Long getLong(Context context,String name){
mSP = context.getSharedPreferences(spName, Activity.MODE_PRIVATE);
return mSP.getLong(name, 0);
}
public static Float getFloat(Context context,String name){
mSP = context.getSharedPreferences(spName, Activity.MODE_PRIVATE);
return mSP.getFloat(name, 0);
}
public static boolean getboolean(Context context,String name){
mSP = context.getSharedPreferences(spName, Activity.MODE_PRIVATE);
return mSP.getBoolean(name, false);
}
}