0

I am storing shared preferences value as a HashSet and when retrieving I see the warning about unchecked casting. What is the most simple and what is the safest solution to ensure bug free implementation here?

class TaskListDataManager(private val context: Context) {
    fun saveList(taskList: TaskList) {
        val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context).edit()

        sharedPreferences.putStringSet(taskList.name, taskList.taskList.toHashSet())

        sharedPreferences.apply()
    }

    fun readList(): ArrayList<TaskList> {
        val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
        val taskLists = sharedPreferences.all.map {
            TaskList(it.key, ArrayList(it.value as HashSet<String>))
        }

        return ArrayList<TaskList>(taskLists)
    }
}

kotlin code example

Cory Robinson
  • 4,616
  • 4
  • 36
  • 53

3 Answers3

3

Apart from the try/catch block, you can also safely unwrap it while putting in the model.

(a.value as? HashSet<String>)?.let {
   TaskList(a.key, ArrayList(it))
}
1

You can try this

try{    
   //code that may throw exception    
}catch(e: SomeException){  
   //code that handles exception  
}finally {  
   // optional finally block  
} 
0

You can try

kotlin.runCatching { }.onFailure {  }
tadev
  • 204
  • 1
  • 5
  • 7
    While this code may provide a solution to the question, it's better to add context as to why/how it works. This can help future users learn, and apply that knowledge to their own code. You are also likely to have positive feedback from users in the form of upvotes, when the code is explained. – Amit Verma Jan 27 '21 at 09:29