历史记录的读取和写入---读取数据和存入数据(做了排序和去重的处理)

需求:一般的搜索界面上都会有热门搜索(我其他的博客有介绍),搜索的历史记录等等,今天这里分析历史记录的写,和存

*效果图
这里写图片描述

如图整体是一个Listview,头布局是从搜索历史文字开始到热门搜索是整个头布局,中间一个listview显示历史记录,脚布局用来处理清楚历史记录的操作,在这里使用的是sp来进行缓存的(只存了10条数据) 下面贴的代码

具体的需求具体分析,这里是写出读取,和写入记入的方法,更具需求在灵活调用即可

(1):读取历史

SharePreferenceUtil.SPACE_HISTORY_TOP_SCAN 名字表示SP的一个存储空间
  /**
     * 读取历史
     *
     * @return list
     */
   private ArrayList<HistorySearch> readeHistoryList() {
        ArrayList<HistorySearch> historyList = new ArrayList<HistorySearch>();
                historyList = SharePreferenceUtil.readHistory(CaptureHistoryActivity.this, SharePreferenceUtil.SPACE_HISTORY_TOP_SCAN);
                break;
        return historyList;
    }

*具体读取的readHistory()的方法封装好了SharePreferenceUtil类直接调用即可
SharePreferenceUtil类中的读取历史的方法readHistory();

    /**
     * 读取搜索历史记录
     *  content  json  createTime  三个字段是HistorySearch的字段,具体字段更具你的需求自己设定字段
     * @param context
     * @param space
     * @return
     */
    public static ArrayList<HistorySearch> readHistory(Context context, String space) {
        ArrayList<HistorySearch> list = new ArrayList<HistorySearch>();
        //获取到传入space,在获取到该命名空间存在sp的的数据
        SharedPreferences sp = context.getSharedPreferences(space, Context.MODE_PRIVATE);
        String content;
        String json;
        long createTime;
        //public static final int SP_DATA_COUNT=10;//设置缓存数据数量   SharePreferenceUtil存储工具类中定义的缓存个数

        for (int i = 0; i <SP_DATA_COUNT; i++) {     //SP_DATA_COUNT   
            content = sp.getString("content" + i, null);
            if(content==null){
                break;
            }
            json=sp.getString("json"+i,null);
            createTime = sp.getLong("createTime" + i, 0);
            HistorySearch hs = new HistorySearch();         //HistorySearch是数据的Bean
            hs.setContent("" + content);
            hs.setCreateTime(createTime);
            hs.setJson(json);
            list.add(hs);
        }
        return list;
    }

(2):存入历史

    /**
     * 写入历史
     *
     * @param content
     */
    public void writeHistory(String content) {
        historyList = new ArrayList<HistorySearch>();
                SharePreferenceUtil.writeHistory(SearchActivity.this, SharePreferenceUtil.SPACE_HISTORY_TOP_SEARCH, content,SharePreferenceUtil.SPACE_HISTORY_TOP_SCAN);

        }
    }

*具体读取的writeHistory()的方法封装好了SharePreferenceUtil类直接调用即可
SharePreferenceUtil类中的读取历史的方法writeHistory();

  /**
     * 写入搜索历史
     *
     * @param context
     * @param content     为当前搜索的东西(当前搜索东西的名字)
     * @space sp命名空间
     */
    public static void writeHistory(Context context, String space, String content,String json) {
        SharedPreferences sp = context.getSharedPreferences(space,  //获取到该命名空间的sp缓存数据
                Context.MODE_PRIVATE);
        ArrayList<HistorySearch> list = readHistory(context, space);//读取历史记录此时为:内存数据
        clearHistory(context, space);                               //清空该命名空间的sp缓存数据
        Iterator<HistorySearch> it = list.iterator();               //迭代器删除,避免并发异常
        while(it.hasNext()) {
            if (it.next().getContent().equals(content)){            //相同的东西,删除内存的数据
                it.remove();
            }
        }
        HistorySearch hs = new HistorySearch();                     //创建该bean对象,存入数据
        hs.setContent(content);
        hs.setJson(json);
        hs.setCreateTime(System.currentTimeMillis());
        list.add(0, hs);                                            //最新搜索的存入到第一位(排序)
        int size = list.size() >= SP_DATA_COUNT ? SP_DATA_COUNT : list.size();  
        SharedPreferences.Editor editor = sp.edit();
        for (int i = size - 1; i >= 0; i--) {                       //遍历存入数据(这里定义的是10条)
            if(!json.isEmpty()){
            editor.putString("json" + i, "" + list.get(i).getJson());
            }
            editor.putString("content" + i, "" + list.get(i).getContent());
            editor.putLong("createTime" + i, list.get(i).getCreateTime());
            editor.commit();
        }
        LogUtil.e("main","####写入历史###"+content);
    }

================================华丽的分割线========================

最后贴出整个SharePreferenceUtil的工具类

package com.lzyc.ybtappcal.util;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;

import com.lzyc.ybtappcal.app.Contants;
import com.lzyc.ybtappcal.bean.HistoryScan;
import com.lzyc.ybtappcal.bean.HistorySearch;
import com.lzyc.zxing.activity.CaptureActivity;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 作者:xujm
 * 时间:2015/12/29
 * 备注:SharePreference的存储工具类
 */
public class SharePreferenceUtil {
    /**
     * 保存在手机里面的文件名
     */
    public static final String FILE_NAME = "share_data";
    //    public static final String HISTORY_NAME = "history_data";
    public static final String IS_LOGIN = "islogin";
    public static final String IS_FIRST = "isfirstInstall";
    //登录信息
    public static final String USER_NAME = "username";
    public static final String PHONE = "phone";
    public static final String NICKNAME = "nickname";
    public static final String NOSETTINGNAME ="noname";
    public static final String KEY_DEVICE_TOKEN="devicetoken";

    //定位城市
    public static final String CITY = "city";
    //选择的已开通城市
    public static final String CITY_OPEN_IS = "cityopenois";
    //定位省份
    public static final String PROVINCE = "province";
    //异地选择的医保省份
    public static final String YBPROVINCE_REIM_CHOOSE = "province.choose";
    //定位地址
    public static final String ADDRESS = "address";
    //当前选择的地址
    public static final String ADDRESS_CURRENT_CHOOSRE = "address.current.choose";
    //定位经纬度
    public static final String LONGITUDE = "longitude";
    public static final String LATITUDE = "latitude";
    //个人中心我的医保城市
    public static final String YBCITY = "ybcity";
    //所在城市,选择所在城市
    public static final String CITY_REIM_SELECTED = "city_selected";
    //职位类型
    public static final String KEY_OBJ_TYPE_JOB = "typejob";
    //职位类型选择是否被记住
    public static final String KEY_BOOL_POP_JOB_ISCHEK = "typejob.popischeck";
    public static final String KEY_BOOL_VERSION_ISNEW = "isnew";
    //首页搜索历史保存空间
    public static final String SPACE_HISTORY_TOP_SEARCH = "space.hoistory.search.top.search";
    //异地报销搜索历史保存空间
    public static final String SPACE_HISTORY_REIMBURSEMENT_SEARCH = "space.hoistory.search.reimbursement.search";
    //首页扫描历史保存空间
    public static final String SPACE_HISTORY_TOP_SCAN = "space.hoistory.search.top.scan";
    //异地报销扫描历史保存空间
    public static final String SPACE_HISTORY_REIMBURSEMENT_SCAN = "space.hoistory.search.reimbursement.scan";
    //关键字:数据缓存
    public static final int SP_DATA_COUNT=10;//设置缓存数据数量

    //搜索时候EditTest填入的文字
    public static final String KEY_WORD = "";
    /**
     * 保存数据的方法,我们需要拿到保存数据的具体类型,然后根据类型调用不同的保存方法
     *
     * @param context
     * @param key
     * @param object
     */
    public static void put(Context context, String key, Object object) {

        SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
                Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();

        if (object instanceof String) {
            editor.putString(key, (String) object);
        } else if (object instanceof Integer) {
            editor.putInt(key, (Integer) object);
        } else if (object instanceof Boolean) {
            editor.putBoolean(key, (Boolean) object);
        } else if (object instanceof Float) {
            editor.putFloat(key, (Float) object);
        } else if (object instanceof Long) {
            editor.putLong(key, (Long) object);
        } else {
            editor.putString(key, object.toString());
        }
        SharedPreferencesCompat.apply(editor);
    }

    /**
     * 得到保存数据的方法,我们根据默认值得到保存的数据的具体类型,然后调用相对于的方法获取值
     *
     * @param context
     * @param key
     * @param defaultObject
     * @return
     */
    public static Object get(Context context, String key, Object defaultObject) {
        SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
                Context.MODE_PRIVATE);

        if (defaultObject instanceof String) {
            return sp.getString(key, (String) defaultObject);
        } else if (defaultObject instanceof Integer) {
            return sp.getInt(key, (Integer) defaultObject);
        } else if (defaultObject instanceof Boolean) {
            return sp.getBoolean(key, (Boolean) defaultObject);
        } else if (defaultObject instanceof Float) {
            return sp.getFloat(key, (Float) defaultObject);
        } else if (defaultObject instanceof Long) {
            return sp.getLong(key, (Long) defaultObject);
        }

        return null;
    }

    /**
     * 移除某个key值已经对应的值
     *
     * @param context
     * @param key
     */
    public static void remove(Context context, String key) {
        SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
                Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.remove(key);
        SharedPreferencesCompat.apply(editor);
    }

    /**
     * 清除所有数据
     *
     * @param context
     */
    public static void clear(Context context) {
        SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
                Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.clear();
        SharedPreferencesCompat.apply(editor);
    }

    /**
     * 查询某个key是否已经存在
     *
     * @param context
     * @param key
     * @return
     */
    public static boolean contains(Context context, String key) {
        SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
                Context.MODE_PRIVATE);
        return sp.contains(key);
    }

    /**
     * 返回所有的键值对
     *
     * @param context
     * @return
     */
    public static Map<String, ?> getAll(Context context) {
        SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
                Context.MODE_PRIVATE);
        return sp.getAll();
    }

    /**
     * 创建一个解决SharedPreferencesCompat.apply方法的一个兼容类
     *
     * @author zhy
     */
    private static class SharedPreferencesCompat {
        private static final Method sApplyMethod = findApplyMethod();

        /**
         * 反射查找apply的方法
         *
         * @return
         */
        @SuppressWarnings({"unchecked", "rawtypes"})
        private static Method findApplyMethod() {
            try {
                Class clz = SharedPreferences.Editor.class;
                return clz.getMethod("apply");
            } catch (NoSuchMethodException e) {
            }

            return null;
        }

        /**
         * 如果找到则使用apply执行,否则使用commit
         *
         * @param editor
         */
        public static void apply(SharedPreferences.Editor editor) {
            try {
                if (sApplyMethod != null) {
                    sApplyMethod.invoke(editor);
                    return;
                }
            } catch (IllegalArgumentException e) {
            } catch (IllegalAccessException e) {
            } catch (InvocationTargetException e) {
            }
            editor.commit();
        }
    }

//关键字: 搜索历史,历史记录,读取搜索历史,写入搜索历史
      /**
     * 写入搜索历史
     *
     * @param context
     * @param content     为当前搜索的东西(当前搜索东西的名字)
     * @space sp命名空间
     */
    public static void writeHistory(Context context, String space, String content,String json) {
        SharedPreferences sp = context.getSharedPreferences(space,
                Context.MODE_PRIVATE);
        ArrayList<HistorySearch> list = readHistory(context, space);
        clearHistory(context, space);
        Iterator<HistorySearch> it = list.iterator();
        while(it.hasNext()) {
            if (it.next().getContent().equals(content)){
                it.remove();
            }
        }
        HistorySearch hs = new HistorySearch();
        hs.setContent(content);
        hs.setJson(json);
        hs.setCreateTime(System.currentTimeMillis());
        list.add(0, hs);
        int size = list.size() >= SP_DATA_COUNT ? SP_DATA_COUNT : list.size();
        SharedPreferences.Editor editor = sp.edit();
        for (int i = size - 1; i >= 0; i--) {
            if(!json.isEmpty()){
                editor.putString("json" + i, "" + list.get(i).getJson());
            }
            editor.putString("content" + i, "" + list.get(i).getContent());
            editor.putLong("createTime" + i, list.get(i).getCreateTime());
            editor.commit();
        }
        LogUtil.e("main","####写入历史###"+content);
    }

    /**
     * 读取搜索历史记录
     *  content  json  createTime  三个字段是HistorySearch的字段,具体字段更具你的需求自己设定字段
     * @param context
     * @param space
     * @return
     */
    public static ArrayList<HistorySearch> readHistory(Context context, String space) {
        ArrayList<HistorySearch> list = new ArrayList<HistorySearch>();
        SharedPreferences sp = context.getSharedPreferences(space, Context.MODE_PRIVATE);
        String content;
        String json;
        long createTime;

        for (int i = 0; i <SP_DATA_COUNT; i++) {
            content = sp.getString("content" + i, null);
            if(content==null){
                break;
            }
            json=sp.getString("json"+i,null);
            createTime = sp.getLong("createTime" + i, 0);
            HistorySearch hs = new HistorySearch();
            hs.setContent("" + content);
            hs.setCreateTime(createTime);
            hs.setJson(json);
            list.add(hs);
        }
        return list;
    }

//关键字:清空历史
    /**
     * 清除历史记录
     *当前用作清空搜索历史,扫描历史
     * @param context
     * @param space
     */
    public static void clearHistory(Context context, String space) {
        SharedPreferences sp = context.getSharedPreferences(space,
                Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.clear();
        editor.commit();
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值