Sharedpreferences Always Get Default Value In My Existing App But When Created New App Its Ok
Solution 1:
When you call apply()
or commit()
the changes are first saved to the app's memory cache and then Android attempts to write those changes onto the disk. What is happening here is that your commit()
call is failing on the disk but the changes are still made to the app's memory cache, as is visible in the source.
It is not enough to read the value from the SharedPreferences as that value might not reflect the true value that is on the disk but only that stored in the memory cache.
What you are failing to do is to check the boolean value returned from the commit()
call, it is probably false for your problematic case. You could retry the commit()
call a couple of times if false is returned.
Solution 2:
Just use below method and check.
Create one Java
class AppTypeDetails.java
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
publicclassAppTypeDetails {
privateSharedPreferences sh;
privateAppTypeDetails() {
}
privateAppTypeDetails(Context mContext) {
sh = PreferenceManager.getDefaultSharedPreferences(mContext);
}
privatestaticAppTypeDetails instance = null;
public synchronized staticAppTypeDetailsgetInstance(Context mContext) {
if (instance == null) {
instance = newAppTypeDetails(mContext);
}
return instance;
}
// get user statuspublicStringgetUser() {
return sh.getString("user", "");
}
publicvoidsetUser(String user) {
sh.edit().putString("user", user).commit();
}
// Clear All Datapublicvoidclear() {
sh.edit().clear().commit();
}
}
Now Set value to SharedPreferences
.
AppTypeDetails.getInstance(MainActivity.this).setUser(<user name>);
Get Value form SharedPreferences
.
StringuserName= AppTypeDetails.getInstance(MainActivity.this).getUser();
Now do any thing with the userName.
Always check
if(userName.trim().isEmpty())
{
// Do anything here.
}
because In SharedPreferences
we set user name blank ("")
or
you can set user name null in SharedPreferences
then you need check
if(userName != null){
//do anything here
}
For clear data from SharedPreferences
.
AppTypeDetails.getInstance(MainActivity.this).setUser("");
or
AppTypeDetails.getInstance(MainActivity.this).clear();
Solution 3:
One thing you could try is to get a new SharedPreference
instance after committing and see what happens:
SharedPreferencespref=this.getSharedPreferences("test", MODE_PRIVATE);
Stringuser= pref.getString("user", default_user);
if (user.equals(default_user)) {
pref.edit().putString("user", "new_user").commit();
SharedPreferencesnewPref=this.getSharedPreferences("test", MODE_PRIVATE);
user = newPref.getString("user", default_user);
}
Your editor is committing a new preference map into disk, but it is possible that the old SharedPreference
instance is not notified of the change.
Solution 4:
Instead of using
edit.commit();
, you should useedit.apply();
. Applywill update the preference object instantly and will save the new values asynchronously, so allowing you to read the latest values.
Source - Also read detailed difference between commit()
and apply()
in this SO Post.
The "Source" post referenced above also states pretty much the same problem and switching to apply()
seems to have resolved the issue there.
Problem statement in the referenced post:
The problem is that when I am accessing this values, it is not returning updated values, it gives me a value of SharedPreferences.
But when I am confirming the data in XML file ,the data updated in that.
PS: And the reason that the same code block is not working on this one app and working on all other apps could also be that you are either using the block at different places or updating the value somewhere else too.
Solution 5:
Your code is right, the code works on any app very well, looks like that in some part of your app the shared preferences are been modified, the only way to find a solution is review all your code, because if this problem only happens on one app, it's somewhere on your app that the shared preferences are been modified, for good practices, you should have only one file class for the management of your preferences on that way you can comment or find usage for a method and you can find where the shared preferences was been modified.
BTW the best way to store an user, password, or any account info is using Account Manager.
For good practices you can see this sample PreferenceHelper class.
publicclassPreferencesHelper {
publicstatic final StringDEFAULT_STRING_VALUE = "default_value";
/**
* Returns Editor to modify values of SharedPreferences
* @param context Application context
* @return editor instance
*/privatestaticEditorgetEditor(Context context){
returngetPreferences(context).edit();
}
/**
* Returns SharedPreferences object
* @param context Application context
* @return shared preferences instance
*/privatestaticSharedPreferencesgetPreferences(Context context){
String name = "YourAppPreferences";
return context.getSharedPreferences(name,
Context.MODE_PRIVATE);
}
/**
* Save a string on SharedPreferences
* @param tag tag
* @param value value
* @param context Application context
*/publicstaticvoidputString(String tag, String value, Context context) {
Editor editor = getEditor(context);
editor.putString(tag, value);
editor.commit();
}
/**
* Get a string value from SharedPreferences
* @param tag tag
* @param context Application context
* @return String value
*/publicstaticStringgetString(String tag, Context context) {
SharedPreferences sharedPreferences = getPreferences(context);
return sharedPreferences.getString(tag, DEFAULT_STRING_VALUE);
}}
Post a Comment for "Sharedpreferences Always Get Default Value In My Existing App But When Created New App Its Ok"