Reputation: 5262
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)
}
}
Upvotes: 0
Views: 979
Reputation: 370
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))
}
Upvotes: 3
Reputation:
You can try this
try{
//code that may throw exception
}catch(e: SomeException){
//code that handles exception
}finally {
// optional finally block
}
Upvotes: 1