1. 程式人生 > >Android歷史記錄的做法思路

Android歷史記錄的做法思路

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);
}