1 package com.example.imsmediatestingapp;
2 
3 import android.content.SharedPreferences;
4 import java.util.HashSet;
5 import java.util.Set;
6 
7 /**
8  * Used as a helper for storing data of different types into the SharedPreferences and handling
9  * converting that data for storage.
10  */
11 public class SharedPrefsHandler {
12     SharedPreferences prefs;
13     SharedPreferences.Editor editor;
14     static final String CODECS_PREF = "CODECS";
15     static final String AMR_MODES_PREF = "AMR_MODES";
16     static final String EVS_BANDS_PREF = "EVS_BANDS";
17     static final String EVS_MODES_PREF = "EVS_MODES";
18 
SharedPrefsHandler(SharedPreferences prefs)19     public SharedPrefsHandler(SharedPreferences prefs) {
20         this.prefs = prefs;
21         editor = prefs.edit();
22     }
23 
24     /**
25      * As SharedPreferences can not save Integer sets, this will convert the Integer set into a
26      * string so it can be saved in the SharedPreferences and converted back into a set when needed.
27      * @param prefKey the key to be used to save the set under
28      * @param set the Integer set to be saved in ShredPreferences
29      */
saveIntegerSetToPrefs(String prefKey, Set<Integer> set)30     public void saveIntegerSetToPrefs(String prefKey, Set<Integer> set) {
31         StringBuilder integerSet = new StringBuilder();
32         for (int item : set) {
33             integerSet.append(item).append(",");
34         }
35 
36         editor.putString(prefKey, integerSet.toString()).apply();
37     }
38 
39     /**
40      * This will convert the String which was previously a set back into a set and return it.
41      * @param prefKey the String value of the SharedPreferences key to retrieve the set data
42      * @return a set containing data from the SharedPreferences
43      */
getIntegerSetFromPrefs(String prefKey)44     public Set<Integer> getIntegerSetFromPrefs(String prefKey) {
45         Set<Integer> set = new HashSet<>();
46         String integerSetString = prefs.getString(prefKey, "");
47         if(!integerSetString.isEmpty()) {
48             String[] integerSet = integerSetString.split(",");
49             for (String item : integerSet) {
50                 set.add(Integer.parseInt(item));
51             }
52         }
53         return set;
54     }
55 
56 }
57