Ahmed Wagdi
Ahmed Wagdi

Reputation: 4391

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.

Upvotes: 0

Views: 154

Answers (2)

art
art

Reputation: 1332

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()

Upvotes: 1

Rami Loiferman
Rami Loiferman

Reputation: 912

You can write it to file using serialisation. HashMap is serialisable. Here is eample Here is another example of how it done
How to save HashMap to Shared Preferences?
And here is how to save file in android
How to Read/Write String from a File in Android (consider using Context.MODE_PRIVATE)

However this may slow down your app because of reading and writing to storage.

Upvotes: 0

Related Questions