Home | History | Annotate | Download | only in storagemanager
      1 /*
      2  * Copyright (C) 2016 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 
     17 package com.android.storagemanager;
     18 
     19 import android.support.v7.preference.Preference;
     20 import android.support.v7.preference.PreferenceGroup;
     21 import android.text.TextUtils;
     22 import android.util.ArrayMap;
     23 
     24 /**
     25  * The PreferenceListCache is a cache of preferences sourced from a {@link PreferenceGroup} which
     26  * allows for the re-use of the same preference object when re-creating a list of preferences.
     27  */
     28 public class PreferenceListCache {
     29     private PreferenceGroup mGroup;
     30     private ArrayMap<String, Preference> mCache;
     31 
     32     /**
     33      * Constructs a PreferenceListCache using the preferences within the given PreferenceGroup.
     34      * @param group The preference group to source preferences from.
     35      */
     36     public PreferenceListCache(PreferenceGroup group) {
     37         mGroup = group;
     38         mCache = new ArrayMap<>();
     39         final int N = group.getPreferenceCount();
     40         for (int i = 0; i < N; i++) {
     41             Preference p = group.getPreference(i);
     42             if (TextUtils.isEmpty(p.getKey())) {
     43                 continue;
     44             }
     45             mCache.put(p.getKey(), p);
     46         }
     47     }
     48 
     49     /**
     50      * Removes a cached preferenced from the cache, if it exists.
     51      * @param key The key of the preference.
     52      * @return The preference, if it exists in the cache, or null.
     53      */
     54     public Preference getCachedPreference(String key) {
     55         return mCache.remove(key);
     56     }
     57 
     58     /**
     59      * Removes the un-reused preferences from the original PreferenceGroup.
     60      */
     61     public void removeCachedPrefs() {
     62         for (Preference p : mCache.values()) {
     63             mGroup.removePreference(p);
     64         }
     65     }
     66 }
     67