1 /*
2  * Copyright (C) 2018 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package com.android.dumpviewer.utils;
17 
18 import android.content.SharedPreferences;
19 import android.text.TextUtils;
20 
21 import java.util.ArrayList;
22 import java.util.Arrays;
23 import java.util.Collection;
24 
25 public class History {
26     private final SharedPreferences mPrefs;
27     private final String mSharedPrefKey;
28     private final int mMaxSize;
29 
30     private static final String SEPARATOR = "\u0001sep\u0001";
31 
32     private ArrayList<String> mItems = new ArrayList<>();
33 
History(SharedPreferences prefs, String sharedPrefKey, int maxSize)34     public History(SharedPreferences prefs, String sharedPrefKey, int maxSize) {
35         mPrefs = prefs;
36         mSharedPrefKey = sharedPrefKey;
37         mMaxSize = maxSize;
38     }
39 
ensureMaxSize()40     private void ensureMaxSize() {
41         while (mItems.size() > mMaxSize) {
42             mItems.remove(0);
43         }
44     }
45 
load()46     public void load() {
47         mItems.clear();
48 
49         mItems.addAll(Arrays.asList(
50                 TextUtils.split(mPrefs.getString(mSharedPrefKey, ""), SEPARATOR)));
51         ensureMaxSize();
52     }
53 
save()54     private void save() {
55         String[] items = mItems.toArray(new String[mItems.size()]);
56         mPrefs.edit().putString(mSharedPrefKey, TextUtils.join(SEPARATOR, items)).apply();
57     }
58 
add(String item)59     public void add(String item) {
60         item = item.trim();
61         if (item.length() == 0) {
62             return;
63         }
64         String fitem = item;
65         mItems.removeIf(v -> v.equals(fitem));
66         mItems.add(item);
67         ensureMaxSize();
68 
69         save();
70     }
71 
addAllTo(Collection<String> col)72     public void addAllTo(Collection<String> col) {
73         for (int i = mItems.size() - 1; i >= 0; i--) {
74             col.add(mItems.get(i));
75         }
76     }
77 }
78