How can I save a HashMap Object into Shared Preferences in Android?
This example demonstrates about How can I save a HashMap to Shared Preferences in Android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.
Shared Preferences allow you to save and retrieve data in the form of key,value pair. In order to use shared preferences, you have to call a method getSharedPreferences() that returns a SharedPreference instance pointing to the file that contains the values of preferences.
Shared Preferences is the way in which one can store and retrieve small amounts of primitive data as key/value pairs to a file on the device storage such as String, int, float, Boolean that make up your preferences in an XML file inside the app on the device storage.
You can save String and custom array list using Gson library. =>First you need to create function to save array list to SharedPreferences. public void saveListInLocal(ArrayList<String> list, String key) { SharedPreferences prefs = getSharedPreferences("AppName", Context.
I use Gson
to convert HashMap
to String
and then save it to SharedPrefs
private void hashmaptest() { //create test hashmap HashMap<String, String> testHashMap = new HashMap<String, String>(); testHashMap.put("key1", "value1"); testHashMap.put("key2", "value2"); //convert to string using gson Gson gson = new Gson(); String hashMapString = gson.toJson(testHashMap); //save in shared prefs SharedPreferences prefs = getSharedPreferences("test", MODE_PRIVATE); prefs.edit().putString("hashString", hashMapString).apply(); //get from shared prefs String storedHashMapString = prefs.getString("hashString", "oopsDintWork"); java.lang.reflect.Type type = new TypeToken<HashMap<String, String>>(){}.getType(); HashMap<String, String> testHashMap2 = gson.fromJson(storedHashMapString, type); //use values String toastString = testHashMap2.get("key1") + " | " + testHashMap2.get("key2"); Toast.makeText(this, toastString, Toast.LENGTH_LONG).show(); }
I would not recommend writing complex objects into SharedPreference. Instead I would use ObjectOutputStream
to write it to the internal memory.
File file = new File(getDir("data", MODE_PRIVATE), "map"); ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream(file)); outputStream.writeObject(map); outputStream.flush(); outputStream.close();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With