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.
Related
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 );
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
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
I want to convert a HashMap to an JSON so I can write it to my apps Shared Preferences as a string.
So this is what I got so far:
HashMap<String, String> colorHashMap = new HashMap<String, String>();
colorHashMap.put("test", "test");
colorHashMap.put("ROT","#FF0000");
JSONObject colorHashMapJasonObj = new JSONObject(colorHashMap);
String JSONString = String.valueOf(colorHashMapJasonObj);
Log.v("JSON: ", JSONString);
editor.putString("standard_colors_JSON", String.valueOf(colorHashMapJasonObj));
String JSONcolorStringFromSP = prefs.getString("standard_colors_JSON", "nothting");
Log.v("JSONcolorStringFromSP: ", JSONcolorStringFromSP);
at JSONString I get the correct value. but at JSONcolorStringFromSP I only get the standard value. So something happens when I try to write my String to my SharedPreferences. But I can't figure out what's wrong there.
Are you missing an apply() or a commit()? Where's your SharedPreferences instance? Here's a complete example:
SharedPreferences prefs = ...;
prefs.edit().putString("somekey", "somevalue").apply();
You have to call the commit() after put some data
eg:
editor.putString("standard_colors_JSON", String.valueOf(colorHashMapJasonObj)).commit();
All SharedPreferences edits have to be called with a .commit() before they're actually saved. Like so:
SharedPreferences.Editor editor = GaggleApplication.getInstance().getSharedPreferences(PREFERENCE_FILE, 0).edit();
editor.putString(name, value);
editor.commit();
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
}
}