Search code examples
androidkotlinhashmap

How to write a hashmap to a file and read it again from another intent


I have got a HashMap in Kotlin that I need to pass to another activity using intent, but its size exceeds the limit to using normal putExtra so I need to write it down in a local file then read it again when I open the second intent.

here is my hashMap private var optionsList: HashMap<String, List<String>> = hashMapOf() and am using HashMap.put method to add data to it .

I've tried to send it using intent.putExtra(HashMap) but it gives an error because it has hundreds of data.

Now all I need to know how to write it to a file and call it again from the second intent.


Solution

  • Generally you should review your app logic, because such a problem can be a sign of a poor design.

    But anyway the next class can be used to store any data class on disk, it uses Gson library for json serialization:

    import android.content.Context
    import androidx.preference.PreferenceManager
    
    import com.google.gson.Gson
    import com.google.gson.JsonSyntaxException
    
    class SharedSettingsProvider<T>(private val gson: Gson,
                                    private val context: Context,
                                    private val type: Class<T>,
                                    private val key: String) {
    
        fun commit(model: T?) {
            PreferenceManager
                    .getDefaultSharedPreferences(context)
                    .edit()
                    .putString(key, model?.let { gson.toJson(it) } ?: "")
                    .apply()
        }
    
        fun retrieve(): T? {
            val mPrefs = PreferenceManager.getDefaultSharedPreferences(context)
            val gsonData = mPrefs.getString(key, "")
            return try {
                gson.fromJson(gsonData, type)
            } catch (ex: JsonSyntaxException) {
                null
            }
        }
    }
    

    The usage:

    data class Data(val optionsList: Map<String, List<String>>)
    val data = Data(mapOf(...))
    
    const val DATA_KEY = "DATA_KEY"
    val provider = SharedSettingsProvider(gson, context, Data::class.java, DATA_KEY)
    
    // write data
    provider.commit(data)
    
    // read data
    val data1 = provider.retrieve()