Search code examples
androidarraylistsharedpreferences

How to read ArrayList key and ArrayList value from SharedPreference?


I have two ArrayList of which one contains value of userNames and the other contains their corresponding userIds.

final ArrayList<String> user_names = new ArrayList<String>();
 user_names.add("rocky");
 user_names.add("pinky");
 user_names.add("chinky");

final ArrayList<String> user_ids = new ArrayList<String>();
user_ids.add("abc");
user_ids.add("efg");
user_ids.add("des");

I have stored user_names as keys and user_ids as the corresponding value in SharePreferences. Whenever user selects a name it's corresponding id should be retrieved from SharedPreference.I have implemented sharedPreference as below to store the value but not sure how to retrieve those values from SharedPreference. Any help would be appreciated.

SharedPreferences keyValues = getSharedPreferences("userId_values", Context.MODE_PRIVATE);
      final SharedPreferences.Editor keyValuesEditor = keyValues.edit();
 final Map<ArrayList<String>, ArrayList<String>> sharedKeyValue = new HashMap<>();

  sharedKeyValue.put(user_names,user_ids);
  keyValuesEditor.apply();
  keyValuesEditor.commit();

Solution

  • You can use Gson to convert your hashmap into the string. then store it in SharedPreference.

    private fun addToSP() {
            val userNames = ArrayList<String>()
            userNames.add("rocky")
            userNames.add("pinky")
            userNames.add("chinky")
    
            val userIds = ArrayList<String>()
            userIds.add("abc")
            userIds.add("efg")
            userIds.add("des")
            
            val keyValues = getSharedPreferences("userId_values", MODE_PRIVATE)
            val keyValuesEditor = keyValues.edit()
            
            val sharedKeyValue: MutableMap<ArrayList<String>, ArrayList<String>> = HashMap()
            sharedKeyValue[userIds] = userIds
           
            val gson = Gson()
            val hashMapString = gson.toJson(sharedKeyValue)
            
            keyValuesEditor.putString("MYHASHMAP", hashMapString)
            keyValuesEditor.apply()
            keyValuesEditor.commit()
    
            
    
            //get from shared prefs
            val storedHashMapString = keyValues.getString("MYHASHMAP", "oopsDintWork")
            val type: Type = object : TypeToken<HashMap<List<String>, List<String>>>() {}.type
            val testHashMap2: HashMap<String, String> = gson.fromJson(storedHashMapString, type)
        }