How to remove some key/value pair from SharedPreferences ? I have put and I to remove that from prefs.
SharedPreferences mySPrefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = mySPrefs.edit();
editor.remove(key);
editor.apply();
Here editor is the sharedPreferences editor.
It is important to note that, unless you're planning on doing something with the return value of the commit() call, there is absolutely no reason for using the synchronous commit() call instead of the asynchronous apply() call.
Keep in mind that if you're calling this from the main/UI thread, the UI is blocked until the commit() has completed. This can take upwards of around 100ms as apposed to about 5ms for the apply. That may not seem like much, but if done continually throughout an application, it will certainly add up.
So, unless you're planning on doing something like this, hopefully on a separate thread:
editor.remove(String key);
boolean success = editor.commit();
if (!success) {
// do something
}
You should instead be doing this:
editor.remove(String key);
editor.apply();
It's very simple:
private SharedPreferences sharedPreferences() {
return PreferenceManager.getDefaultSharedPreferences(mContext);
}
public void clearSharedPreferences() {
sharedPreferences()
.edit()
.remove(SOME_KEY_1)
.remove(SOME_KEY_2)
.remove(SOME_KEY_3)
.apply();
}
SharedPreferences.Editor.remove(key)
commit();
Here is how I tacked this issue.
First I created an instance of SharedPreference as
SharedPreferences mobilePreference;
then I used this sharedPreference as
mobilePreference = this.getSharedPreferences("in.bhartisoftwares.amit.allamitappsthree", Context.MODE_PRIVATE);
Here "in.bhartisoftwares.amit.allamitappsthree" is my package name and I am using Context.MODE_PRIVATE, because I want to manipulate this shared preference only for this package name.
Then I am deleting the selected sharedPreference (key of my sharedPreference is mobileString) as follows:
mobilePreference.edit().remove("mobileString").commit();
See the code as full below:
SharedPreferences mobilePreference = this.getSharedPreferences("in.bhartisoftwares.amit.allamitappsthree", Context.MODE_PRIVATE);
mobilePreference.edit().remove("mobileString").commit();
Information
Just check sharedpref class is extended to Map that's why there is remove method
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = prefs.edit();
editor.remove(String key);
editor.apply();
Here editor is the sharedPreferences editor.
Related
I have a Sharedpreferences to check if the user has activated the pro section with InAppPurchase and I check it every time Mainactivity is opens, like this:
SharedPreferences s = c.getSharedPreferences("app" , MODE_PRIVATE);
String value = s.getString(key , " ");
Log.i("myapp" , value);
and if some one tries to change the value manually my app warns him .so I tried to test my app's security and changed the value manually with text editor from data/data/com.myapp.package/shared_prefs/ let's say the value was 39m49ur3.I changed it a to 87mjr83.Then I started the app and the value from the logs stil was 39m49ur3 . I closed the app and started it again but no change was seen except when I clear the RAM of my device then start the app , finally then the value I got from the logs is what really is in the shared_prefs folder.
What can I do about this?
Save like this,
SharedPreferences pref = c.getSharedPreferences("app", MODE_PRIVATE);
Editor editor = pref.edit();
editor.putString("myapp", "string value");
editor.commit();
Get Like this,
pref.getString("myapp", null);
//to save String in shared preferences
public void put(String key, String value) {
mSharedPreferences.edit().putString(key, value).apply();
}
//to get value from shared preferences
public String get(String key, String defaultValue) {
return mSharedPreferences.getString(key, defaultValue);
}
Try to use
editor.apply();
Instead of
editor.commit();
Unlike commit(), which writes its preferences out to persistent storage synchronously, apply() commits its changes to the in-memory SharedPreferences immediately but starts an asynchronous commit to disk and you won't be notified of any failures.
I am saving some data to SharedPreference from a fragment and want use these data in other fragments. But I want to perform fragment transaction only if SharedPreferences are saved successfully, otherwise, other fragments would not be able to retrieve data (since using those SharedPreference values to retrieve data).
My code:
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{
... ... ... ... ... ... ... ... ...
public void setSharedPref(String key, String val) {
SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString(key, val);
editor.commit();
}
public String fetchSharedPref(String key) {
SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE);
String val = sharedPref.getString(key, Constant.SHARED_PREF_DEFAULT_MSN);
return val;
}
}
How can I be sure that SharedPreferences are saved successfully?
Is there any way to implement a callback that will be invoked only if SharedPreferences saved successfully?
From the docs.
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.saved_high_score), newHighScore);
editor.commit();
Then go and check commit() method here.
Return type: boolean
Description: Returns true if the new values were successfully written to persistent storage.
Find the solution :
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("Your Key", "Your value");
boolean savedOrNot = editor.commit();
if(savedOrNot){
// Successfully saved
}else{
// Not saved
}
Form Documentation
apply()
This saves your data into memory immediately and saves the data to
disk on a separate thread. So there is no chance of blocking the main
thread (your app won’t hang).
It is the preferred technique but has only been available since
Gingerbread (API 9, Android 2.3).
commit()
Calling this will save the data to the file however, the process is
carried out in the thread that called it, stopping everything else
until the save is complete. It returns true on successful completion,
false on failure.
Use commit() if you need confirmation of the success of saving your
data or if you are developing for pre-Gingerbread devices. commit()
has been available since API 1
so your can check status at editor.commit();
commit() returns true if the save works, false otherwise.
commit() returns true if the save works, false otherwise.
You can alter your method as follows.
public boolean setSharedPref(String key, String val) {
SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString(key, val);
return editor.commit()
}
Difference between apply and commit https://developer.android.com/reference/android/content/SharedPreferences.Editor.html
The editor.commit() will return boolean value , which will let you know if data has been saved.
If you would like to analyze all the data saved in shared preferences and sqlite ,then i would recommend using facebook stetho
Its a debug bridge for android , you can check all of your shared preferences data and sql databases for debugging.
I've got a really weird problem with my shared preferences. I'm using them to store the user-ID, different settings and so on. I'm using an activity which switches fragments if a user has clicked an item in my menu (I'm using Menu-Drawer).
After every login I store the user profile. This works perfect. After doing this I can restart the app, kill it from the memory, I can even restart my device and my values are still stored. But when I switch the fragment, e.g I'm in the home view and click "about app" in the menu, everything is gone. My values are empty.
Where it gets even weirder: If I force the activity to reload the fragment by selecting the home-item while I'm already in the home view, it's still stored. Only if I replace it with a different type of fragment everything is lost.
I don't have any idea why the app behaves like this. It's all in the same activity with the same context. I'm always using getActivity to get my context inside the fragment.
Here's a simplified snippet of my code to store it.
public static void storeUserProfile(Context context, LoginEvent event, String userId, String emailAddress, String passwordHash) {
SharedPreferences userPrefs = context.getSharedPreferences(AppConfig.USER_PREFS, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = userPrefs.edit();
editor.clear();
editor.putString("username", event.userName);
editor.putString("id", userId);
editor.putString("email", emailAddress);
editor.commit();
}
This is how I switch my fragments:
HomeFeedFragment fragment = new HomeFeedFragment();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.commit();
Try this snippet, it can be accessed from all activities/ fragments in your app.
Declare these methods first..
public static void putPref(String key, String value, Context context) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(key, value);
editor.commit();
}
public static String getPref(String key, Context context) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
return preferences.getString(key, null);
}
Then call this when you want to put a pref:
putPref("myKey", "mystring", getApplicationContext());
call this when you want to get a pref:
getPref("myKey", getApplicationContext());
Using fragments, does not work with getSharedPreferences() only with
PreferenceManager.getDefaultSharedPreferences (getActivity ());
Thank you very much for the fast responses! I've found the error myself. For the about view, I'm loading an html file which will be stored in shared preferences too. I haven't thought about the fact that sharedpreferences are just an xml file so I think that the html string made the xml file invalid.
I've noticed that my prefs.getString(key, defaultValue) weren't returning the defaultValue, they were returning an empty String. So I've removed the html storing and do this in a different way.
But thank you for your comments!
I had the same problem, i solved by changing the key string of my sharedpreferences
I was using :
SharedPreferences userPrefs = context.getSharedPreferences("MuslimActive", Context.MODE_PRIVATE);
I changed with :
SharedPreferences userPrefs = context.getSharedPreferences("muslim_active", Context.MODE_PRIVATE);
Anything past 2.3 and MODE_MULTI_PROCESS is disable by default, and if multiple instances of the same SharedPreferences exist MODE_MULTI_PROCESS will need to be set.
Try:
getSharedPreferences(AppConfig.USER_PREFS, Context.MODE_MULTI_PROCESS);
Also, make sure you are consistently using AppConfig.USER_PREFS in your method calls.
I have 2 processes in my application. From one process i save data in to SharedPreferences.
From second process - retrieve. When i retrieve data, i receive SharedPreferences with old data(i check xml file and see, that currently data in file and data that was received are different). It looks like this data was cached. I changed saving methods (commit/apply) but no result.
PS: just for example http://pastebin.com/Zx2ffvSg
//saving
{ ...
SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_PRIVATE);
SharedPreferences.Editor prefsEditor = myPrefs.edit();
prefsEditor.putString(MY_NAME, "Sai");
prefsEditor.putString(MY_WALLPAPER, "f664.PNG");
prefsEditor.commit();
... }
//retrieving
// when i call getData() I put "this" as argument.
public void getData(Context context){
SharedPreferences myPrefs = context.getSharedPreferences("myPrefs", MODE_PRIVATE);
...}
The solution is add to neccesary flags Context.MODE_MULTI_PROCESS flag when open shared preference (Available in API Level 11 and up)
I have an Android application in which I have my preferences in an XML file, which works fine. I now want to set one of the preferences using code instead of displaying the entire preference screen, how would I go about doing this?
I assume by preferences you are referring to your application's preferences and not Android phone settings.
To store preferences between runs of you application you need to do the following
Create a SharedPreferences object
SharedPreferences settings = getSharedPreferences(String n, MODE_PRIVATE);
String n identifies your preferences and the second argument is the mode they'll be accessed
Instantiate an Editor object
SharedPreferences.Editor editor = settings.edit();
Note: do not try settings.editor.edit(), this will not make a persistent object and the code below will not work
Write your preferences to the buffer
editor.put...(String, value)
There are numerous put function, putString, putBoolean, etc. The String is the key ("version", "good run") and the value is the value ("1.5.2", true)
Flush the buffer
editor.commit();
This actually writes you put to the preferences. If your app crashes before this line then the preferences will not be written. There is also a documented bug: commit() is supposed to return a boolean indicating success or failure. Last I checked it always returned false.
These preferences will by stored on the phone and will only be accessible to your application.
More documentation is here
I tried this but didn't work:
SharedPreferences settings = getSharedPreferences(String n, MODE_PRIVATE);
Try this instead:
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
You can save something in the sharedpreferences by using below code
public static void save(String valueKey, String value) {
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(context);
SharedPreferences.Editor edit = prefs.edit();
edit.putString(valueKey, value);
edit.commit();
}
To read preferences:
public static String read(String valueKey, String valueDefault) {
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(context);
return prefs.getString(valueKey, valueDefault);
}