How can I know that Android SharedPreferences are saved successfully? - android

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.

Related

sharedpreferences value not updated

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.

SharedPreferences does not store value

I am currently working with SharedPreferences in Android, and I encountered a weird behavior I cannot explain. This is my code:
SharedPreferences appPreferences = this.getSharedPreferences("settings", Context.MODE_PRIVATE);
appPreferences.edit().putBoolean("launched_before", true);
appPreferences.edit().apply();
appPreferences = null;
appPreferences = this.getSharedPreferences("settings", Context.MODE_PRIVATE);
boolean test = appPreferences.getBoolean("launched_before", false); //this is false
The value that I write to my SharedPreferences is not being saved. I know I could use getDefaultSharedPreferences(), but I do not want to do this here, as the default file stores other values.
When I use commit() instead of apply(), the return value of commit() is true, but I still cannot load the file correctly.
This happens because your code doesn't do what you think. When you call edit(), it does not start an "edit transaction". Instead it returns a new instance of Editor object each time you call it. So let's look at this code:
SharedPreferences appPreferences = getSharedPreferences("settings", Context.MODE_PRIVATE);
// Here you create a FIRST Editor object, which stores the modification
// You never call apply() on this object, and thus your changes are dropped.
appPreferences.edit().putBoolean("launched_before", true);
// Here you create a SECOND Editor object (which has no modifications)
// and you call apply() on it, thus changing nothing.
appPreferences.edit().apply();
You created the first editor object which you put settings in, but you called apply on the second editor object which had no changes. Since you never called apply() on the editor object which had modification, your change was never saved.
The fix is obvious - use a single instance of Editor for your modification, and call apply/commit on this instance:
SharedPreferences appPreferences = this.getSharedPreferences("settings", Context.MODE_PRIVATE);
SharedPreferences.Editor ed = appPreferences.edit();
ed.putBoolean("launched_before", true);
ed.apply();
Here you can use as key "com.yourdomain.yourapp.your_key_name" and for each value use another key...try this
private SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(appContext);
public void putBoolean(String key, boolean value) {
checkForNullKey(key);
preferences.edit().putBoolean(key, value).apply();
}
public boolean getBoolean(String key) {
return preferences.getBoolean(key, false);
}
public void checkForNullKey(String key){
if (key == null){
throw new NullPointerException();
}
}

Data cache in Shared Preference

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)

How to remove some key/value pair from SharedPreferences?

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.

Android - How Do I Set A Preference In Code

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

Categories

Resources