Android: writing string to SharedPreferences does not work - android

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();

Related

How can I add elements inside HashMap and save it? [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 );

Wanted to store this custom listview text using shared preference on user click

I want to store this custom listview text using shared preference when user will click on that star image (P.S - I don't want to use a database for this) and also wants to retrieve that text(all selected text as an ArrayList) in another activity.
Now I am able to store this text as an ArrayList in my shared preference I but inside my getView() method of custom adapter my ArrayList get reinitialize again and again can anyone help me out
Like this demo example
when user will click on this star image
and in favorite activity will retrieve ArrayList from shared preference
You have to write your arraylist as a json into Sharedpreference
public void saveArrayList(ArrayList<String> list, String key){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
SharedPreferences.Editor editor = prefs.edit();
Gson gson = new Gson();
String json = gson.toJson(list);
editor.putString(key, json);
editor.apply();
}
public ArrayList<String> getArrayList(String key){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
Gson gson = new Gson();
String json = prefs.getString(key, null);
Type type = new TypeToken<ArrayList<String>>() {}.getType();
return gson.fromJson(json, type);
}
https://freakycoder.com/android-notes-40-how-to-save-and-get-arraylist-into-sharedpreference-7d1f044bc79a

Cannot load string from Fragment's shared preferences

I am trying to save and load a string value from a fragment's shared preferences. However, the string I am committing to the preferences does not load back from the preferences. Here is my code.
// Prefs string handle
String NAME = "myPref";
// Get default prefs for the fragment
SharedPreferences defaultPrefs =
PreferenceManager.getDefaultSharedPreferences(getActivity());
// Commit a string to prefs
defaultPrefs.edit().putString(NAME, "Hello world!");
defaultPrefs.edit().commit();
// Load the string just commited to prefs
String commitedString = defaultPrefs.getString(NAME,"defaultString");
// Print the loaded string
// logs defaultString
// does not log Hello world!
Log.v(TAG,"commitedString value is "+commitedString);
You are editing, putting a String, not committing, then editing again, putting nothing, and then committing.
Change
defaultPrefs.edit().putString(NAME, "Hello world!");
defaultPrefs.edit().commit();
To
defaultPrefs.edit().putString(NAME, "Hello world!").commit();
change this
defaultPrefs.edit().putString(NAME, "Hello world!");
defaultPrefs.edit().commit();
to this:
SharedPreferences.Editor editor = defaultPrefs.edit();
editor.putString(NAME, "Hello world!");
editor.commit();
and it should work
//This always seemed to work for me
Context context = YourFragmentName.this;
String NAME = "";
SharedPreferences share = context.getSharedPreferences("prefs", 0);
share.getString(NAME, NAME);
SharedPreferences.Editor editor = share.edit();
editor.putString(NAME, "myPref");
editor.apply();
//then get your string
String commitedString = share.getString(NAME, "");

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