How can I add elements inside HashMap and save it? [Android] - android

I'm new with HashMap, how can I save permanently and add other items when I reopen the application?
For example:
private HashMap<String, Recognition> registered = new HashMap<>();
public void register(String name, Recognition rec) {
registered.put(name, rec);
}
I can see all items inside registered using:
for (Map.Entry<String, Recognition> entry : registered.entrySet()) {
final String name = entry.getKey();
... }
But when I close and reopen app, I can't see all objects saved inside registered.
I see lot of people using SharedPreferences, but I don't know how to add items inside the pre-saved hashmap.

You can do it indirectly this way:
//writing into file
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString( key, hashmap.getValue() );
editor.commit();
//reading from file
SharedPreferences pref = getPreferences(Context.MODE_PRIVATE);
for( i = 0;i < size;i++) )
pref.getString( i , defaultValue );

Related

Shared Preferences for Arraylist

I've a bunch of strings in an arraylist.
I want to save some of the strings in a shared preferences.
like if user selects a sting whose index is 3, I want to store that particular string in a shared preference.
Is it possible?
Please let me know.
I hope that this code will help you understand it
int id = selectedItemNum;
ArrayList<String> list = new ArrayList<String>();
list.add("Item1");
list.add("Item2");
list.add("Item3");
list.add("Item4");
String selectedString = list.get(id);
String APP_PREFERENCES = "savedStrings";
SharedPreferences mySharedPreferences = getSharedPreferences(APP_PREFERENCES, Context.MODE_PRIVATE);
Editor editor = mySharedPreferences.edit();
editor.putString("savedString"+id, selectedString);
editor.apply();
To save data to SharedPreferences:
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
for(int i=0; i<arraylist.size(); i++){
sharedPreferences.edit().putString("TAG" + Integer.toString(i)
,arraylist.get(i)).apply();
}
To get data from SharedPreferences:
sharedPreferences.getString("TAG" + "x", null); x is a number position in array list

How to get each value from set after storing set in sharedpreference

I am using this code for string array of string values in shared preferences.
SharedPreferences preferences = context.getSharedPreferences(
"browser_opened_urls", 0);
Set<String> urls = new HashSet<String>();
for (int i = 0; i < Browser.mainWebViewFlipper.getChildCount(); i++) {
WebView webview = (WebView) Browser.mainWebViewFlipper
.getChildAt(i);
urls.add(webview.getUrl());
}
preferences.edit().putStringSet("URLs", urls).commit();
But i am not getting how to get the values when retrieving set from shared preferences. Can anyone help ?
This is my code when i am getting set.
SharedPreferences preferences = getSharedPreferences("browser_opened_urls", 0);
Set<String> urls = preferences.getStringSet("URLs", null);
Now can anyone tell me how to get each stored value from "urls" ?
Ok i found answer myself.
SharedPreferences preferences = getSharedPreferences("browser_opened_urls", 0);
Set<String> urls = preferences.getStringSet("URLs", null);
if (urls != null) {
Iterator<String> iterator = urls.iterator();
while (iterator.hasNext()) {
String url = iterator.next();
}
Use getString method to retrieve the data from sharedPreferences
As mentioned in the android api reference.
Use method:-
getStringSet(String key, Set<String> defValues)
The solution to your question is SharedPreferences prefs=preferences.getStringSet(String URLs, Set<String> urls);
This is assuming you want to store in a new object for retrieving the old set

Multiple SharedPreferences in an android app

SharedPreferences pref = getSharedPreferences("user1", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putString("firstName", firstnameString);
editor.commit();
SharedPreferences pref = getSharedPreferences("user2", Context.MODE_PRIVATE);
...
I am trying to create multiple sharedpreferences using the above code and trying to access all the sharedpreference names i.e user1,user2 etc using the code below.
But i am getting a NULLPointerException while accessing even though the sharedpreference is created.
Map<String,?> allsharedpref = pref.getAll();
if(allsharedpref!=null){
for(Map.Entry<String, ?> entry : allsharedpref.entrySet()){
Toast.makeText(this, entry.getKey()+"\n", Toast.LENGTH_LONG).show();
}
To get values from all SharedPreferences which you have created. you will need to read file names from shared_prefs :
File prefsdir = new File(getApplicationInfo().dataDir,"shared_prefs");
String[] list = prefsdir.list();
String[] preflist = new String[list.length()];
for(int i=0;i<list.length(),i++){
String preffile = list[i].substring(0, list[i].length()-4);
preflist[i]=preffile;
}
Now use preflist to get values from all SharedPreferences:
for(int index=0;index<preflist.length(),index++){
SharedPreferences spPref = getSharedPreferences(preflist[index], MODE_PRIVATE);
Map<String,?> allsharedpref = spPref.getAll();
if(allsharedpref!=null){
for(Map.Entry<String, ?> entry : allsharedpref.entrySet()){
Toast.makeText(this, entry.getKey()+"\n", Toast.LENGTH_LONG).show();
}
}
getSharedPreferences() can only be called after onCreate() has been called on an Activity.

How do I update a sharedpreference variable in this way?

I have a sharedpreference var with values like these:
key0,value
key1,value
key3,value
key5,value
key6,value
key7,value
key10,value
What I want to do is to get a new sharedpreference value with items sorted sequentially like these:
key0,value
key1,value
key2,value
key3,value
key4,value
key5,value
key6,value
How do I do this?
Thank you in advanced.
You can use a workaround like this:
SharedPreferences shp = context.getSharedPreferences("yourSHP", MODE_PRIVATE);
//begin & end are to integers. For your case: 0 and 6 to get form key0 to key6
for(int i=begin;i<=end;i++){
String value = shp.getString("key"+i, "defaultValue");
//.....Here you can do whatever you want with your values
}
I hope this would help!!
SharedPreferences.Editor editor = getSharedPreferences(PREFS_NAME, 0).edit();
for( Entry<String, String> entry : testMap.entrySet() )
editor.putString( entry.getKey(), entry.getValue() );
editor.commit();
I did the following workaround. I don't know if there is another faster way to do it:
SharedPreferences shpTH = mContext.getSharedPreferences("PrefsTH", ListadoImagenesSubidasMain.MODE_PRIVATE);
Map<String,?> keysTH = shpTH.getAll();
List<String> imgTH = new ArrayList<String>();
for(Map.Entry<String,?> entry : keysTH.entrySet()){
imgTH.add(entry.getValue().toString());
}
SharedPreferences newPrefsTH = mContext.getSharedPreferences("PrefsTH", ListadoImagenesSubidasMain.MODE_PRIVATE);
newPrefsTH.edit().clear().commit();
int contTH = 0;
for(String item : imgTH){
SharedPreferences.Editor editorTH = newPrefsTH.edit();
editorTH.putString("urlTH" + contTH, item);
editorTH.commit();
contTH++;
}
Firstly I copy all the values to a list. Then I empty the sharedpreferences var and finally I put all the values got from the list filled previously in the empty sharedpreferences.

how to store and retrieve (key,value) kind of data using saved preferences android

I have a hash map table as below,
HashMap<String, String> backUpCurency_values = new HashMap<String, String>();
and i want to store these value for future use.. how can i do that?
Edit:
i will store to Country names and currencyvalue as key and value pair...
You should just use a for-each loop and iterate through the map like this:
SharedPreferences.Editor editor = getSharedPreferences(PREFS_NAME, 0).edit();
for( Entry<String, String> entry : backUpCurency_values.entrySet() )
editor.putString( entry.getKey(), entry.getValue() );
editor.commit();
Then when you need to get your values back for later use you do the following (provided that this SharedPreference-object is reserved for currency):
SharedPreferences prefs = getSharedPreferences(PREFS_NAME, 0);
for( Entry<String, ?> entry : prefs.getAll().entrySet() )
backUpCurency_values.put( entry.getKey(), entry.getValue().toString() );
You can use SharedPreferences.
settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
//The below step you can repeat to put all the key value pair from the hashmap to the shared preference
editor.putString("Key", Value);
// Commit the edits!
editor.commit();
And to retrieve later use
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean silent = settings.getString(<Key>, <defaultvalue>);
There are a few different ways to approach this. With nothing more to go on than the info that you want to store a HashMap to SharedPreferences, I can only make assumptions.
First thing I'd ask is whether you will be storing other things in the SharedPreferences as well- I'll assume you will.
Here is how I would approach it:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("backUpCurency", stringify(backUpCurency_values));
editor.commit();
You may want to see what stringify does:
// turns a HashMap<String, String> into "key=value|key=value|key=value"
private String stringify(HashMap<String, String> map) {
StringBuilder sb = new StringBuilder();
for (String key : map.keySet()) {
sb.append(key).append("=").append(map.get(key)).append("|");
}
return sb.substring(0, sb.length() - 1); // this may be -2, but write a unit test
}
Then you can just parse that string with known structure upon reading the shared preferences later.
private HashMap<String, String> restoreIt() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
String backup = settings.getString("backUpCurency", "");
HashMap<String, String> map = new HashMap<String, String>();
for (String pairs : backup.split("|")) {
String[] indiv = pairs.split("=");
map.put(indiv[0], indiv[1]);
}
return map;
}
You can use SharedPreference like this:
SharedPreferences s_pref=PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
Editor edit=s_pref.edit();
edit.putString("key","value");
edit.commit();
later you can use it like:
String s=s_pref.getString("key","default value");
But,you must have list of keys you have saved values with,into SharedPreferences so that you can get values easily at the time of retrieving them.
To store the values use this code
SharedPreferences preferences = getSharedPreferences(
PREF_FILE_NAME, MODE_PRIVATE);
if (value.equals("")) {
boolean storedPreference = preferences.contains(key);
if (storedPreference) {
SharedPreferences.Editor editor = preferences.edit();
editor.remove(key); // value to store
Log.d("KEY",key);
editor.commit();
}
}else{
SharedPreferences.Editor editor = preferences.edit();
editor.putString(key, value); // value to store
Log.d("KEY",key);
editor.commit();
}
To retrieve the values use this code
SharedPreferences preferences = getSharedPreferences(
PREF_FILE_NAME, MODE_PRIVATE);
Map<String, String> map = (Map<String, String>) preferences.getAll();
if(!map.isEmpty()){
Iterator<Entry<String, String>> iterator = map.entrySet().iterator();
while(iterator.hasNext()){
Map.Entry pairs = (Map.Entry)iterator.next();
pairs.getKey()+pairs.getValue();
//write code here
}
}

Categories

Resources