当前位置:   article > 正文

android存放本地数据

android开发本地记录

介绍

android中向本地存放数据的方式有,数据库,sharedpreference和文件。如果想提出一个能用于存放缓存的话,数据库需要建立相应的表格,sharedPreference好像不可以,文件的话,用序列化就可以。所以就采用文件的方式。

问题

采用文件存放缓存有一个问题,就是有些对象是不能被序列化的,比如bitmap。我采用的方法就是,将这些对象前面加上transient标记,在反序列化的时候将这样的对象用能序列化的对象(比如图片的路径)新建出来。好吧,贴个能在本地做缓存的模版

解决


  1. /**
  2. * 用于做本地缓存,T需要覆盖equals()方法和hashCode()方法
  3. */
  4. public class BufferStore<T extends Serializable & Comparable<T>> {
  5. private final String mBuffPath;
  6. /**
  7. * @param buffPath
  8. * 存放缓存的路径
  9. * */
  10. public BufferStore(String buffPath) {
  11. mBuffPath = buffPath;
  12. }
  13. /**
  14. * @param list
  15. * 向本地写入的缓存数据
  16. * @param maxCount
  17. * 本地缓存的最大数据量
  18. * */
  19. public synchronized void write(List<T> list, int maxCount) {
  20. if (list == null || maxCount <= 0) {
  21. return;
  22. }
  23. // 获得缓存数据
  24. List<T> oldList = get();
  25. // 将新数据加入
  26. for (T t : list) {
  27. // 不存在才加入
  28. if (!oldList.contains(t)) {
  29. oldList.add(t);
  30. }
  31. }
  32. // 将数据排序
  33. Collections.sort(oldList);
  34. // 删除多余数据
  35. for (int i = oldList.size() - 1; i >= maxCount; i--) {
  36. oldList.remove(i);
  37. }
  38. // 写入本地
  39. put(oldList);
  40. }
  41. /**
  42. * 读取缓存数据
  43. *
  44. * @return 缓存数据,数据为空时返回长度为0的list
  45. * */
  46. public synchronized List<T> read() {
  47. return get();
  48. }
  49. /**
  50. * 向本地写入数据
  51. * */
  52. private void put(List<T> list) {
  53. try {
  54. // 打开文件
  55. FileOutputStream fos = new FileOutputStream(mBuffPath);
  56. // 将数据写入文件
  57. ObjectOutputStream oos = new ObjectOutputStream(fos);
  58. oos.writeObject(list);
  59. // 释放资源
  60. oos.close();
  61. fos.close();
  62. } catch (FileNotFoundException e) {
  63. e.printStackTrace();
  64. } catch (IOException e) {
  65. e.printStackTrace();
  66. }
  67. }
  68. /**
  69. * 从本地读取数据
  70. * */
  71. @SuppressWarnings("unchecked")
  72. private List<T> get() {
  73. List<T> list = new ArrayList<T>();
  74. try {
  75. File file = new File(mBuffPath);
  76. if (!file.exists()) {
  77. return list;
  78. }
  79. // 打开文件
  80. FileInputStream fis = new FileInputStream(mBuffPath);
  81. // 读取文件
  82. ObjectInputStream ois = new ObjectInputStream(fis);
  83. list = (List<T>) ois.readObject();
  84. // 释放资源
  85. ois.close();
  86. fis.close();
  87. } catch (FileNotFoundException e) {
  88. e.printStackTrace();
  89. } catch (IOException e) {
  90. e.printStackTrace();
  91. } catch (ClassNotFoundException e) {
  92. e.printStackTrace();
  93. }
  94. return list;
  95. }
  96. }

其中read和write是读写方法。write中有个maxCount值是用来指定缓存中最多缓存多少条的。为什么T要实现Comparable?缓存需要按照时间排序。

总结

实现了一个能在本地缓存任意实现了Serializable和Compareable同时覆盖equals()方法的类的工具。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Cpp五条/article/detail/669238
推荐阅读
相关标签
  

闽ICP备14008679号