Search code examples
androidlistkotlinsavesharedpreferences

How to save a list with Boolean values in SharedPreferences in kotlin?


I want to save this list in SharedPreferences with Boolean values:

val listTheme = mutableListOf( false,false,true,false)

how can this be done? in kotlin language in android studio


Solution

  • You can use the Kotlin Serialization library to store data structures (including classes and lists) as JSON strings - there are other libraries too. But for something simple like this, you can probably get away with doing it yourself:

    val listTheme = mutableListOf(false, false, true, false)
    
    // convert each value to a specific character (produces a string)
    val serialized = listTheme.map { if (it) '1' else '0' }.joinToString("")
    
    // convert each character to a true or false value (produces a list)
    val deserialized = serialized.map { it == '1' }
    
    print(" original: $listTheme\n serialized: $serialized\n deserialized: $deserialized")
    
    >>>  original: [false, false, true, false]
     serialized: 0010
     deserialized: [false, false, true, false]
    

    Then you can just throw it in a String preference, and convert it back to a list when you fetch it later.