How to save HashMap to Shared Preferences?
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();
Saving hash map into SharedPreferences
Function to Insert HashMap into SharedPreference
private void insertToSP(HashMap<String, List<String>> jsonMap) {
String jsonString = new Gson().toJson(jsonMap);
SharedPreferences sharedPreferences = getSharedPreferences("HashMap", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("map", jsonString);
editor.apply();
}
Function to read hashMap from SharedPreference
private HashMap<String, List<String>> readFromSP(){
SharedPreferences sharedPreferences = getSharedPreferences("HashMap", MODE_PRIVATE);
String defValue = new Gson().toJson(new HashMap<String, List<String>>());
String json=sharedPreferences.getString("map",defValue);
TypeToken<HashMap<String,List<String>>> token = new TypeToken<HashMap<String,List<String>>>() {};
HashMap<String,List<String>> retrievedMap=new Gson().fromJson(json,token.getType());
return retrievedMap;
}
Add this dependancy in gradle
implementation 'com.google.code.gson:gson:2.6.2'
Save hashmap in SharedPreferences
Gson is not recognizing the anonymous class that results from doing it that way.
Try initializing the map without using the {{}}
construct.
e.g.
Map<String, String> userMap = new HashMap<String , String>();
for(int i = 0; i < userList.size(); i++ ) {
String id= userList.get(i).getId();
String name = userList.get(i).getName();
put(id, name);
}
Gson gson = new Gson();
String jsonString = gson.toJson(userMap);
SessionManager sessionManager=new SessionManager(LoginActivity.this);
sessionManager.saveMap(jsonString);
To convert this json back to a Map<String, String>
you can use TypeToken
as suggested here.
Gson gson = new Gson();
Type type = new TypeToken<Map<String, String>>() {}.getType();
Map<String, String> nameEmployeeMap = gson.fromJson(jsonString, type);
Android: Save map to SharedPreferences?
When saving more complex types in Android, I would suggest using gson
. Gson is Google's JSON parsing library, and even if you're not using JSON, you can convert your Objects
into a JSON String, and store that easily.
For example, you can convert your list of Objects
into a String
like this.
val list : List<MyObject> // ... add items to your list
// Convert to JSON
val string = gson.toJson(list)
// Store it into Shared Preferences
preferences.putString("list", string).apply()
And then you can easily get it back into a list like this.
// Fetch the JSON
val string = preferences.getString("list", "")
// Convert it back into a List
val list: List<MyObject> = gson.fromJson(string, object : TypeToken<List<MyObject>>() {}.type)
How to save hashmap to shared preference?
Try this to save objects in SharedPreferences.
you need to add Gson library to your project.
public void putMyObject(String key , Object obj) {
//AnyVehicleModel mvehicle =new AnyVehicleModel();
SharedPreferences.Editor editor = preferences.edit();
Gson gson = new Gson();
String json = gson.toJson(obj);
editor.putString(key,json);
editor.apply();
}
public MyObject getMyObject(String key) {
Gson gson = new Gson();
String json = preferences.getString(key,"");
MyObject obj = gson.fromJson(json, MyObject.class);
if (obj== null){return new MyObject ();}
return obj;
}
how to store ArrayList HashMap String, String data into sharedpreferences?
Convert your array or object to JSON and store into shared pref
for storing:
SharedPreferences db=PreferenceManager.getDefaultSharedPreferences(context);
Editor collection = db.edit();
Gson gson = new Gson();
String arrayList1 = gson.toJson(arrayList);
collection.putString(key, arrayList1);
collection.commit();
for retrieving
SharedPreferences db=PreferenceManager.getDefaultSharedPreferences(context);
Gson gson = new Gson();
String arrayListString = db.getString(key, null);
Type type = new TypeToken<ArrayList<ArrayObject>>() {}.getType();
ArrayList<ArrayObject> arrayList = gson.fromJson(arrayListString, type);
How can I store a HashMap Integer, String in android using shared preferences?
Hey I found a way in the end :)
I just changed the HashMap I had to format and then did the following to save the contents:
SharedPreferences.Editor editor = getSharedPreferences(PREFS_NAME, 0).edit();
for( Entry entry : backUpCurency_values.entrySet() )
editor.putString( entry.getKey(), entry.getValue() );
editor.commit();
and the following to retrieve the HashpMap:
SharedPreferences prefs = getSharedPreferences(PREFS_NAME, 0);
for( Entry entry : prefs.getAll().entrySet() )
backUpCurency_values.put( entry.getKey(), entry.getValue().toString() );
Retrieve hashmap data SharedPreferences
There is no support for HashMap
in SharedPreferences. So, you can't save the HashMap by converting it to a string directly, but you can convert it to JSON string. You can use google-gson in this case. Something like this:
First, include the dependency:
compile 'com.google.code.gson:gson:2.8.2'
Saving from HashMap object to preference:
Editor prefsEditor = mPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(map);
prefsEditor.putString("YourHashMap", json);
prefsEditor.commit();
Get HashMap object from preference:
Gson gson = new Gson();
String json = mPrefs.getString("YourHashMap", "");
HashMap map = gson.fromJson(json, HashMap.class);
Related Topics
Arrayadapter in Android to Create Simple Listview
How to Create a User-Defined Function in SQLite
Jelly Bean Datepickerdialog --- How to Cancel
Android Webview - Webpage Should Fit the Device Screen
How to Use Web Camera in Android Emulator to Capture a Live Image
How to Get Higher Precision of "Cpu%" Than That from Top Command
How to Set Up Android Sdk for Command Line Development on Linux
Remove App from Recent Apps Programmatically
No Generated R.Java File in My Project
Android Gridlayout with Dynamic Number of Columns Per Row
How to Place Fragment Arrylist Scrollabletabsactivity
Read Only File System on Android
Android: Creating Custom Preference
Install Shows Error in Console: Install Failed Conflicting Provider
How to Get File in Assets from Android Ndk
Updating Android UI Using Threads
How to Set Textview Textstyle Such as Bold, Italic
Java.Lang.Illegalargumentexception: View Not Attached to Window Manager