public class SavaDataSPUtil<T> {
private static final String TAG = "MainActivity";
private static SharedPreferences mSp = null;
private static SavaDataSPUtil mSavaDataSPUtil = null;
//创建单列标记
private static String flag=null;
//获取保存数据标记
private String dataFlag=null;
private static Context mContext;
//初始化上下文
public static void initContext(Context context) {
mContext = context;
}
//私有的构造方法
private SavaDataSPUtil(String tag) {
this.dataFlag=tag;
this.flag = tag;
Log.i(TAG,"FLAG标志:"+flag);
mSp = mContext.getSharedPreferences(tag, Context.MODE_PRIVATE);
}
//根据不同的标签创建不同的SavaDataSPUtil单列对象
public static SavaDataSPUtil getInstance(String tag) {
if (flag==null){
mSavaDataSPUtil=new SavaDataSPUtil(tag);
return mSavaDataSPUtil;
}else
if (flag!=null){
if (flag.equals(tag)){
return mSavaDataSPUtil;
}else
if (!flag.equals(tag)){
mSavaDataSPUtil=new SavaDataSPUtil(tag);
return mSavaDataSPUtil;
}
}
return null;
}
//保存数据
public void savaData(List<T> list) {
Gson gson = new Gson();
Type type = new TypeToken<List<T>>() {
}.getType();
String json = gson.toJson(list, type);
mSp.edit().putString(dataFlag, json).commit();
}
public List<T> getData() {
List<T> list=new ArrayList<>();
Gson gson=new Gson();
Type type=new TypeToken<List<T>>(){}.getType();
Log.i(TAG,"获取数据的dataFlag标志:"+dataFlag);
String string = mSp.getString(dataFlag, "null");
list=gson.fromJson(string,type);
return list;
}
}
根据不同的标记创建不同的单列对象,保存、获取SharedPreference数据更加方便、快捷。