本文在CSDN博客首发 转载请注明出处 http://blog.csdn.net/u011071427/article/details/50979085 本文出自Allen李的博客
Android开发过程中会经常需要做历史记录。
列出的常见的四种思路:
1.存在云端服务器上。
优点:存储交给服务器来做,减少app内存
缺点:每次都需要请求网络,比较费时间
2.存在本地数据库中。
优点:操作比较简单
缺点:需要写很多附加的工具类
3.存在ShaerdPreferences里。
优点:操作简单方便
缺点:只能存储基本数据类型
4.存在sd卡里的txt文件中。
优点:操作比较简单,类似于SharePreferences。
缺点:也需要写比较多附加的工具类
移动端的历史记录属于小容量存储,所以不建议写到数据库和服务器上。建议使用第三种,或者第四种方式进行存储。
这里对如何把历史记录保存在SharePreferences种,做一个简单的介绍
/**
* 读取历史纪录
* @param context
* @param historyKey
* @return
*/
public static List<String> readHistory(Context context, String historyKey){
String history = (String) SPUtils.get(context, historyKey, "");
String[] histroys = history.split(";");
List<String> list = new ArrayList<String>();
if(histroys.length > 0){
for (int i = 0; i < histroys.length; i++) {
if(histroys[i] != null && histroys[i].length()>0){
list.add(histroys[i]);
}
}
}
return list;
}
/**
* 插入历史纪录
* @param context
* @param historyKey
* @param value
*/
public static void insertHistory(Context context, String historyKey, String value) {
String history = (String) SPUtils.get(context, historyKey, "");
int historyLength = (int) SPUtils.get(context, historyKey + "Length", -1);
boolean repeat = false;
if (history != null && history.length() > 0) {
String[] historys = history.split(";");
for (int i = 0; i < historys.length; i++) {
if (historys[i].equals(value)) {
repeat = true;
}
}
if (repeat) {
return;
}else{
if (historyLength == -1){
if (historys.length < 3) {
SPUtils.put(context, historyKey, value + ";" + history);
}else{
SPUtils.put(context, historyKey, value + ";" + history.substring(0, history.lastIndexOf(";")));
}
}else{
if (historys.length < historyLength) {
SPUtils.put(context, historyKey, value + ";" + history);
}else{
SPUtils.put(context, historyKey, value + ";" + history.substring(0, history.lastIndexOf(";")));
}
}
}
} else {
SPUtils.put(context, historyKey, value);
}
}
/**
* 设置历史记录长度
* @param context
* @param historyKey
* @param length
*/
public static void setHistoryLength(Context context,String historyKey,int length){
SPUtils.put(context,historyKey + "Length", length);
}