Am using SharedPreferences to store list of values. What I need is to remove specific value from SharedPreferences.Below is my code am using to remove. But its not working.
prefs= DetailActivity.this.getSharedPreferences("itemFKID",Context.MODE_PRIVATE);
edit=prefs.edit();
//edit.clear();
edit.remove(itemFkId);
edit.commit();
Below is Screenshot that contains values even after edit.remove() compiles.
Here am inserting values into SharedPreferences
prefs= DetailActivity.this.getSharedPreferences("itemFKID",Context.MODE_PRIVATE);
edit=prefs.edit();
for (int i = 0; i < Config.favouritesList.size(); i++) {
edit.putString("itemFKIDValue" +i, Config.favouritesList.get(i));
}
edit.putInt("itemFKIDLength", Config.favouritesList.size());
edit.commit();
The documentation for SharedPreferences.Editor has two bits that are relevant to your question:
All changes you make in an editor are batched, and not copied back to the original SharedPreferences until you call commit() or apply()
And
when committing back to the preferences, all removals are done first, regardless of whether you called remove before or after put methods on this editor
So you'll have to step over the commit() call before you see the value removed.
Finally found the mistake. Key passed in remove() is wrong. Instead of edit.remove(itemFKIDValue) I have used edit.remove(itemFkID). Thanks for the time guys.
Related
I have a little doubt about the SharedPreferences in Android.
To delete a preference, we mainly have two options:
First:
SharedPreferences.Editor edit = (Editor) getSharedPreferences(Constants.APP_DEFAULT_PREF, MODE_PRIVATE).edit();
edit.putString(Constants.PREF_ACC, null);
edit.commit();
Second:
SharedPreferences.Editor edit = (Editor) getSharedPreferences(Constants.APP_DEFAULT_PREF, MODE_PRIVATE).edit();
edit.remove(Constants.PREF_ACC);
edit.commit();
In either case, fetching Constants.PREF_ACC value from SharedPreferences will return null.
I was wondering which one should I prefer. Is there any memory related issues in either of them? What will the System.gc behavior be with them?
Theoretically remove is better than put(null), because it removes both the key and value (once committed) instead of mapping (and keeping) the key to a null value.
But judging by the Android 5.1.1 implementation, they are equivalent :
...
String k = e.getKey();
Object v = e.getValue();
// "this" is the magic value for a removal mutation. In addition,
// setting a value to "null" for a given key is specified to be
// equivalent to calling remove on that key.
if (v == this || v == null) {
if (!mMap.containsKey(k)) {
continue;
}
mMap.remove(k);
} else {
...
That is also what one of the putXXX methods (putStringSet) documentation says :
Passing null for this argument is equivalent to calling remove(String)
with this key.
I would recommend using remove.
When we putString or remove nothing is done, it is just marked in the Editor as TO BE DONE and gets done only when commit is called
And when the commit is called all the remove calls are executed before the put calls. So it is better to use the remove calls to remove something from the Editor.
Judging by the docs of the interface SharedPreferences.Editor for remove(String) :
Mark in the editor that a preference value should be removed, which
will be done in the actual preferences once commit() is called.
Note that when committing back to the preferences, all removals are
done first, regardless of whether you called remove before or after
put methods on this editor.
… and for putInt(int) :
Set an int value in the preferences editor, to be written back once
commit() or apply() are called.
… there seem to be only one striking difference: remove(String) calls will be "done first, regardless of whether you called remove before or after put methods".
That said, I really doubt the actual order of execution won't matter much to average use-cases, so you could just choose either one of those methods and be completely fine.
p.s., I'm still looking for the concrete class of SharedPreferences.Editor which might provide more clues about this. Will update as soon as I found one.
Here is code I am Using to create and store value in Preference.
outgoing is String variable.
SharedPreferences sp = getSharedPreferences(outgoing, Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putString("PhoneNo","Hi");
editor.commit();
Here is the code to get value from SharedPreference.
SharedPreferences sp
=getSharedPreferences(outgoing,Activity.MODE_PRIVATE);
String calln = sp.getString("PhoneNo","0");
Toast.makeText(mContext, "SHARED"+calln,Toast.LENGTH_LONG).show();
You should probably call the getSharedPreferences on the context from which you are accessing them.
Source
Therefore, depending on how you can access your context, if you pass it to some other activity or in an asynchronous task, here are some examples of usage:
this.getSharedPreferences(outgoing, Activity.MODE_PRIVATE);
context.getSharedPreferences(outgoing, Activity.MODE_PRIVATE);
getApplicationContext().getSharedPreferences(outgoing, Activity.MODE_PRIVATE);
Also, one way you can test your stuff is to use a listener when SharedPreferences get changed:
onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key)
Called when a shared preference is changed, added, or removed.
here is how to do that
You can also use the Preference Manager to obtain the SharedPreferences:
PreferenceManager.getSharedPreferences(YOUR_CONTEXT).getString(
"PhoneNo", "0");
Or to store them:
PreferenceManager.getSharedPreferences(YOUR_CONTEXT).edit().putString(
"PhoneNo", "Hi").commit();
The most likely reason that Shared Preference always returns the default value is that you saved the value in one preference file and then tried to retrieve it in another preference file. This can happen if you do call getPreferences() from different Activities, because getPreferences() creates a different preference file based on the activity it is created in.
Solution
The easiest solution is to always get your shared preferences like this:
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
This will use a single preference file for the entire app.
Alternate solution
If for some reason you need to use different preference files, then you can do
final static String PREF_FILE_1 = "pref_file_1";
...
SharedPreferences sharedPref = context.getSharedPreferences(PREF_FILE_1, Context.MODE_PRIVATE);
Just make sure you always use the right file name for the preferences you are trying to save and retrieve.
Local preferences
If you really only need a preference for a specific Activity, then you can use getPreferences(Context.MODE_PRIVATE). Just don't expect to be able to retrieve the values from another Activity in the same way.
See also
This answer describes the differences between the various ways of obtaining SharedPreferences.
Difference between getDefaultSharedPreferences and getSharedPreferences
Mess with the shared preferences of android - which function to use?
change this Activity.MODE_PRIVATE to this Activity.MODE_MULTI_PROCESS, issue is probably due to different context during storing value and accessing value.
When putting values, try changing this:
SharedPreferences sp = getSharedPreferences(outgoing, Activity.MODE_PRIVATE);
to this:
SharedPreferences sp = getApplicationContext().getSharedPreferences(outgoing, Activity.MODE_PRIVATE);
Same when getting values - don't forget to add getApplicationContext() in your call to SharedPreferences
EDIT:
Check that your "outgoing" String is the exact same in both Activities
Im trying to use androids sharedpreferences, I´ve logged everything and the code below really commits the string set. The problem is when I force close the app and start again, the settings.getStringSet returns an empty set. No errormessages anywhere.
I´ve tried PreferenceManager.getDefaultSharedPreferences but that does not work for me either.
Thanks for you time.
public static final String PREFS_NAME = "MyPrefsFile";
private static final String FOLLOWED_ROUTES = "followedRoutes";
and later on when saved is called:
public void onFollowClicked(View view){
SharedPreferences settings = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
Set<String> follows = settings.getStringSet(FOLLOWED_ROUTES, new HashSet<String>());
follows.add(routeId);
editor.putStringSet(FOLLOWED_ROUTES, follows);
editor.commit();
}
You can also work around the bug mentioned by g00dy this way:
Get the set from sharedPreferences and save it in a variable.
Then just delete the set in sharedpreferences before adding it again when saving.
SharedPreferences.Editor editor= sharedPref.edit();
editor.remove("mSet");
editor.apply();
editor.putStringSet("mSet", mSet);
editor.apply();
Make sure to use apply() or commit() twice.
Alternatively, if you are working in Kotlin simply :
PreferenceManager.getDefaultSharedPreferences(applicationContext)
.edit {
this.remove("mSet")
this.apply()
this.putStringSet("mSet", mSet)
}
Take a look here.
Also for refference:
SharedPreferences
SharedPreferences.Editor
EDIT:
There's actually a bug with this one, see here. An extract from there:
This problem is still present on the 17 API level.
It is caused because the getStringSet() method of the
SharedPreferences class doesn't return a copy of the Set object: it
returns the entire object and, when you add new elements to it, the
commitToMemory method of the SharedPrefencesImpl.EditorImpl class see
that the existing value is equal to the previous one stored.
The ways to workaround this issue is to make a copy of the Set
returned by SharedPreferences.getStringSet or force the write to
memory using other preference that always change (for example, a
property that stores the size of the set each time)
EDIT2:
There might be a solution here, take a look.
I've implemented a OnPreferenceChangeListener on two preference object in my preference page ( extends PreferenceActivity)
But ever since the preference value isn't updated upon change,
I even tried using :
SharedPreferences sharedPreferences = getSharedPreferences("myCustomSharedPrefs",
Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(preference.getKey(), Integer.parseInt(newValue.toString()));
editor.commit();
Where preference is the changed preference and newValue is the new value...
What am I missing ?
Thanks
You need to return true to get the value updated, see the Android documentation.
Can you see if preference.getKey() is giving the correct name? Can you print in your console and see. Code looks clean to me. May be the name is different than what is expected.
Also make sure that the value is also having the correct value.
I have stored the username and the password in the sharedpreference.
And I am displaying the username in every activity like Welcome "Username".
But at the time of logout I have put one checkbox in the dialog box.If the check box is checked the sharedpreference value should be clear. So I don't know how to do it.Please help me out of it. Thank you.
SharedPreferences settings = getSharedPreferences("MyPreferences", 0);
if (settings.contains("mykey")) {
SharedPreferences.Editor editor = settings.edit();
editor.remove("mykey");
editor.apply();
}
The method to clear the sharedpreferences is this
http://developer.android.com/reference/android/content/SharedPreferences.Editor.html#clear()
With this you dont delete the xml
Editor.clear();
Editor.commit();
You have to use remove method which is simple and described here. The only parameter is the Key you have used to save this preference.
1st method
Your_sharedprefrence_name..clear();
Your_sharedprefrence_name.commit();
2nd Method
Your_sharedprefrence_name.clear().commit();
3rd Method(When u want to clear the arraylist of sharedprefrence put it in loop)
Your_sharedprefrence_name.remove(String.valueOf(i)).clear().commit();