So, I'm trying to store HashMap
on Android. I think it's better to use internal storage, but I don't understand how to save HashMap
in it and then read it later. Can someone explain how to do that properly, please?
There are counters with their own names and values. I want to load them onсe when some activity was started, work with them (change, delete, add new), and then save that data to use next time. Right now I use HashMap because it's easy to delete/add values.
HashMap<String, Integer> counters;
It stores the data in the pair of Key and Value. HashMap contains an array of the nodes, and the node is represented as a class. It uses an array and LinkedList data structure internally for storing Key and Value.
Description: In Step 1, we have created an object of HashMap collection. In Step 2, we have used put method to add key value pair in the data structure that we have created in step 1. In Step 3, we have used for each loop to retrieve the values from the HashMap object.
A HashMap is a structure allowing one to store (key,value) items. A hash function pairs each key to an array index where the value will be stored.
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.
SharedPreferences also store data in key-value pair as hashmap, so why not get all key-values from hashmap and store into map, as it:
SharedPreferences pref= getContext().getSharedPreferences("Your_Shared_Prefs"),
Context.MODE_PRIVATE);
SharedPreferences.Editor editor= pref.edit();
for (String s : map.keySet()) {
editor.putString(s, map.get(s));
}
To fetch values you can use:
public abstract Map<String, ?> getAll ()
http://developer.android.com/reference/android/content/SharedPreferences.html#getAll%28%29
use:
SharedPreferences pref= getContext().getSharedPreferences("Your_Shared_Prefs"),
Context.MODE_PRIVATE);
HashMap<String, String> map= HashMap<String, String> pref.getAll();
for (String s : map.keySet()) {
String value=map.get(s);
//Use Value
}
Code is not compiled, so it may have some minor errors, but should work.
Try this
HashMap<String, String> hashMap = new HashMap<String, String>();
hashMap.put("key", "value");
Intent intent = new Intent(this, MyOtherActivity.class);
intent.putExtra("map", hashMap);
startActivity(intent);
and Another way is HERE
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