package com.dp.util;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
/**
* 本地保存工具类
*/
public class PreferencesUtil {
private static int MODE = Context.MODE_PRIVATE;// 定义访问模式为私有模式
private static String PREFERENCENAME = "DPOPREFERENCE";
/**保存boolean值*/
public static boolean setBooleanValue(Context context, String key,
boolean value) {
Editor editor = context.getSharedPreferences(PREFERENCENAME, MODE)
.edit();
editor.putBoolean(key, value);
return editor.commit();
}
/**取出boolean值*/
public static Boolean getBooleanValue(Context context, String key ,boolean defValue) {
SharedPreferences settings = context.getSharedPreferences(
PREFERENCENAME, MODE);
return settings.getBoolean(key, defValue);
}
/**保存string值*/
public static boolean setStringValue(Context context, String key, String value) {
Editor editor = context.getSharedPreferences(PREFERENCENAME, MODE)
.edit();
editor.putString(key, value);
return editor.commit();
}
/**取出string值*/
public static String getStringValue(Context context, String key ,String defValue) {
SharedPreferences settings = context.getSharedPreferences(
PREFERENCENAME, MODE);
return settings.getString(key, defValue);
}
/**保存list值*/
public static boolean setListValue(Context context, String key, List value) {
Editor editor = context.getSharedPreferences(PREFERENCENAME, MODE)
.edit();
//将list的大小保存,方便之后取值
editor.putInt(key+"_size",value.size());
for (int i = 0; i < value.size(); i++) {
editor.putString(key+"_"+i, value.get(i)+"");
}
return editor.commit();
}
/**取出list值*/
public static List<String> getListValue(Context context, String key) {
List<String> list = new ArrayList<String>();
SharedPreferences settings = context.getSharedPreferences(
PREFERENCENAME, MODE);
int size = settings.getInt(key+"_size", 0);
for (int i = 0; i < size; i++) {
list.add(settings.getString(key+"_"+i, ""));
}
return list;
}
}
本地保存数据Preferences
最新推荐文章于 2023-06-25 22:54:37 发布