Shared Preferences clear on app restarting - java

I am using Shared Preferences in my Android application.
It works fine, but when I restart the application, all the shared preferences values are gone.
Why?

Without code is diffucult to resolve. Anyway, i suppose you don't reinstall every time application before launch it. So probably you don't commit changes to shared preference. From Saving Key-Value Sets:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.saved_high_score), newHighScore);
editor.commit();
Check your code to verify presence of commit() instruction.

1st are you doing more things in the if statement? Because you are creating two variables that do nothing and get destroyed after this clause
2nd do you even assign "text" preference at all when not it is not loading because you get the default null back
I'm sorry I thought it was your code but then it goes to assad

I think you are not commiting those changes. SharedPreferences.Editor.commit() is must applied after putting the values. Commit ensures the values has been saved.

Consider this the accepted answer :
I don't know why, but it is working by just putting your prefs code inside the async task:
prefss = getSharedPreferences(ACCOUNT_PREFS_NAME, MODE_MULTI_PROCESS);
new AsyncSave(favNamesList).execute();
private static class AsyncSave extends AsyncTask<Void, Void, Boolean> {
String favNamesList;
AsyncSave(String favNamesList) {
this.favNamesList = favNamesList;
}
#Override
protected Boolean doInBackground(Void... params) {
prefss.edit().putString("favNamesList", strings).apply();
return null;
}
}

Related

How can I CHANGE shared preferences values from another activity?

I got a few activities and one called SettingsActivity. I've created shared preferences there (just one Boolean value for now, but it'll be more).
I want to store values in there and access (not only access but actually change) the values of it in all of my other activities. How can I change this Boolean value from other activity?
Thank you so much!!!
When you have created a SharedPreference, its already available in all other activities for being accessed from them.
I hope while you are saving this, you are doing something like the following.
private SharedPreferences prefs;
prefs = getSharedPreferences("YOUR_APP_NAME", Context.MODE_PRIVATE);
prefs.edit().putBoolean("SOME_KEY", booleanValue).apply();
Now when you are getting it from another activity you need to do something like the following.
private SharedPreferences prefs;
prefs = getSharedPreferences("YOUR_APP_NAME", Context.MODE_PRIVATE);
prefs.getBoolean("SOME_KEY", defValue);
SharedPreference stores key-value pair and hence you can find the value against the key wherever you want to get it.
Now you can change it from any activity. Just use the same key for referencing it from other activities.
private SharedPreferences prefs;
prefs = getSharedPreferences("YOUR_APP_NAME", Context.MODE_PRIVATE);
prefs.edit().putBoolean("SOME_KEY", otherBooleanValue).apply();

Android: SharedPreferences loses 2 of its variables after closing app

i save a couple variables via SharedPreferences without a problem. However, 2 of these variables are reset after i restart the app. I think the problem happens while saving, not while loading, because if i change the default value for loading, it doesnt even use that value, it just goes to 0.
I call this method in onPause:
public void saveStats() {
SharedPreferences pref = getSharedPreferences(SHARED_PREFERENCES, this.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putLong(SECONDS_PLAYED_TOTAL_FILE, secondsPlayedTotal);
editor.putFloat(CURRENCY_GAINED_TOTAL_FILE, currencyGainedTotal);
editor.apply();
}
And load onResum:
SharedPreferences pref = getSharedPreferences(SHARED_PREFERENCES, this.MODE_PRIVATE);
SECONDS_PLAYED_TOTAL = pref.getLong(SECONDS_PLAYED_TOTAL_FILE, 0);
CURRENCY_GAINED_TOTAL = pref.getFloat(CURRENCY_GAINED_TOTAL_FILE, 0);
The variables are public and static.
I save and load similar public static variables without a problem, but those 2 are the only ones i save at onPause().
Any idea?
You could try replacingeditor.apply(); with editor.commit()
From the Android documentation:
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.
Link:
https://developer.android.com/reference/android/content/SharedPreferences.Editor.html#apply()

Writing tests for preferences, keep getting `android.content.res.Resources$NotFoundException` when accessing preferences

I am just starting to learn testing on Android and this is driving me crazy. The feature works fine but I cannot get my tests to run. I am trying to read a value from SharedPreferences and compare it to the content of a TextView. I am using Espresso on Android Studio 2.3.3.
This line String player1Name = sharedPreferences.getString(context.getString(R.string.KEYplayerOneDefaultNameSetting), context.getString(R.string.playerOne)); causes this android.content.res.Resources$NotFoundException: String resource ID #0x7f09004d exception. This is essentially the same code that I use in my Fragments to access shared preferences.
I could not find anything referencing this same problem. I feel like I just have a simple configuration error but I can't figure it out. Thanks in advance.
Here is my entire test:
#Test
public void setsPlayerNamesFromSettings(){
Context context = getInstrumentation().getContext();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
String player1Name = sharedPreferences.getString(context.getString(R.string.KEYplayerOneDefaultNameSetting), context.getString(R.string.playerOne));
onView(withId(R.id.LpCalculatorTextPlayer1Name)).check(matches(withText(player1Name)));
String player2Name = sharedPreferences.getString(context.getString(R.string.KEYplayerTwoDefaultNameSetting), context.getString(R.string.playerTwo));
onView(withId(R.id.LpCalculatorTextPlayer2Name)).check(matches(withText(player2Name)));
}
If it's any assistance, here's code from my Fragment that access SharedPreferences
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getContext());
mLpCalculatorModel.setLpDefault(Integer.parseInt(preferences.getString(getString(R.string.KEYdefaultLpSetting), "8000")));
mLpCalculatorModel.setPlayer1Name(preferences.getString(getString(R.string.KEYplayerOneDefaultNameSetting), getString(R.string.playerOne)));
mLpCalculatorModel.setPlayer2Name(preferences.getString(getString(R.string.KEYplayerTwoDefaultNameSetting), getString(R.string.playerTwo)));
mLpCalculatorModel.setAllowsNegativeLp(preferences.getBoolean(getString(R.string.KEYallowNegativeLp), false));
tvPlayer1Lp.setText(Integer.toString(mLpCalculatorModel.getLpDefault()));
tvPlayer2Lp.setText(Integer.toString(mLpCalculatorModel.getLpDefault()));
getInstrumentation().getContext()
This returns a Context representing your androidTest source set. If your resources are elsewhere (e.g., main), use:
getInstrumentation().getTargetContext()

How to update main activity to know that prefs are changed?

I have
SharedPreferences myPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
and
myPreferences.getBoolean("checkbox", true)
So, how can my main activity know when user change preferences state?
For example if user don't wont to get notifications any more.
Thanks.
You could either re-read all the preferences in Activity.onResume(), or as long as your main activity launches the preferences activity (e.g. from a menu), you could launch with startActivityForResult(Intent, int) and re-read all the preferences in onActivityResult(int, int, Intent).
I have also found it sufficient to re-check each relevant preference before starting the appropriate behavior (i.e. before issuing the Notification for your example).
You need to implement the onSharedPreferenceChangeListener interface. Then register to receive change updates in your onCreate/onStart:
myPreferences.registerOnSharedPreferenceChangeListener();
In your listener you do something like this:
#Override
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
if (key.equals("MyKey")) {
// Do something.
} else if (key.equals("MyOtherKey")) {
// Do something else.
}
}
Remember to remove the listener in onStop/onDestroy.
You can create a static boolean that is changed whenever a preference is changed, or when your preference activity is started. The purpose of this boolean is to let your main activity know the preferences are dirty and need to be reloaded. They should be reloaded onResume if the mDirty flag is true.
Another option is to just reload all the preferences onResume, regardless. This may not be as efficient, but if you don't have loads of preferences, it's fine.
The most efficient way would be to set onPreferenceChanged listeners for all your prefs in your prefs activity, the prefs then notify the activity only when they actually change. This solves the case when your user enters your prefs activity, but doesn't actually change anything.

How do I get the SharedPreferences from a PreferenceActivity in Android?

I am using a PreferenceActivity to show some settings for my application. I am inflating the settings via a xml file so that my onCreate (and complete class methods) looks like this:
public class FooActivity extends PreferenceActivity {
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
addPreferencesFromResource(R.xml.preference);
}
}
The javadoc of PreferenceActivity PreferenceFragment states that
These preferences will automatically save to SharedPreferences as the user interacts with them. To retrieve an instance of SharedPreferences that the preference hierarchy in this activity will use, call getDefaultSharedPreferences(android.content.Context) with a context in the same package as this activity.
But how I get the name of the SharedPreference in another Activity? I can only call
getSharedPreferences(name, mode)
in the other activity but I need the name of the SharedPreference which was used by the PreferenceActivity. What is the name or how can i retrieve it?
import android.preference.PreferenceManager;
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
// then you use
prefs.getBoolean("keystring", true);
Update
According to Shared Preferences | Android Developer Tutorial (Part 13) by Sai Geetha M N,
Many applications may provide a way to capture user preferences on the
settings of a specific application or an activity. For supporting
this, Android provides a simple set of APIs.
Preferences are typically name value pairs. They can be stored as
“Shared Preferences” across various activities in an application (note
currently it cannot be shared across processes). Or it can be
something that needs to be stored specific to an activity.
Shared Preferences: The shared preferences can be used by all the components (activities, services etc) of the applications.
Activity handled preferences: These preferences can only be used within the particular activity and can not be used by other components of the application.
Shared Preferences:
The shared preferences are managed with the help of getSharedPreferences method of the Context class. The preferences are stored in a default file (1) or you can specify a file name (2) to be used to refer to the preferences.
(1) The recommended way is to use by the default mode, without specifying the file name
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
(2) Here is how you get the instance when you specify the file name
public static final String PREF_FILE_NAME = "PrefFile";
SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);
MODE_PRIVATE is the operating mode for the preferences. It is the default mode and means the created file will be accessed by only the calling application. Other two modes supported are MODE_WORLD_READABLE and MODE_WORLD_WRITEABLE. In MODE_WORLD_READABLE other application can read the created file but can not modify it. In case of MODE_WORLD_WRITEABLE other applications also have write permissions for the created file.
Finally, once you have the preferences instance, here is how you can retrieve the stored values from the preferences:
int storedPreference = preferences.getInt("storedInt", 0);
To store values in the preference file SharedPreference.Editor object has to be used. Editor is a nested interface in the SharedPreference class.
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", storedPreference); // value to store
editor.commit();
Editor also supports methods like remove() and clear() to delete the preference values from the file.
Activity Preferences:
The shared preferences can be used by other application components. But if you do not need to share the preferences with other components and want to have activity private preferences you can do that with the help of getPreferences() method of the activity. The getPreference method uses the getSharedPreferences() method with the name of the activity class for the preference file name.
Following is the code to get preferences
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
int storedPreference = preferences.getInt("storedInt", 0);
The code to store values is also the same as in case of shared preferences.
SharedPreferences preferences = getPreference(MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", storedPreference); // value to store
editor.commit();
You can also use other methods like storing the activity state in database. Note Android also contains a package called android.preference. The package defines classes to implement application preferences UI.
To see some more examples check Android's Data Storage post on developers site.
If you don't have access to getDefaultSharedPreferenes(), you can use getSharedPreferences(name, mode) instead, you just have to pass in the right name.
Android creates this name (possibly based on the package name of your project?). You can get it by putting the following code in a SettingsActivity onCreate(), and seeing what preferencesName is.
String preferencesName = this.getPreferenceManager().getSharedPreferencesName();
The string should be something like com.example.projectname_preferences. Hard code that somewhere in your project, and pass it in to getSharedPreferences() and you should be good to go.
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());
Or you can use this object https://github.com/kcochibili/TinyDB--Android-Shared-Preferences-Turbo
which simplifies everything even further
Example:
TinyDB tinydb = new TinyDB(context);
tinydb.putInt("clickCount", 2);
tinydb.putFloat("xPoint", 3.6f);
tinydb.putLong("userCount", 39832L);
tinydb.putString("userName", "john");
tinydb.putBoolean("isUserMale", true);
tinydb.putList("MyUsers", mUsersArray);
tinydb.putImagePNG("DropBox/WorkImages", "MeAtlunch.png", lunchBitmap);
having to pass context around everywhere is really annoying me. the code becomes too verbose and unmanageable. I do this in every project instead...
public class global {
public static Activity globalContext = null;
and set it in the main activity create
#Override
public void onCreate(Bundle savedInstanceState) {
Thread.setDefaultUncaughtExceptionHandler(new CustomExceptionHandler(
global.sdcardPath,
""));
super.onCreate(savedInstanceState);
//Start
//Debug.startMethodTracing("appname.Trace1");
global.globalContext = this;
also all preference keys should be language independent, I'm shocked nobody has mentioned that.
getText(R.string.yourPrefKeyName).toString()
now call it very simply like this in one line of code
global.globalContext.getSharedPreferences(global.APPNAME_PREF, global.MODE_PRIVATE).getBoolean("isMetric", true);
if you have a checkbox and you would like to fetch it's value ie true / false in any java file--
Use--
Context mContext;
boolean checkFlag;
checkFlag=PreferenceManager.getDefaultSharedPreferences(mContext).getBoolean(KEY,DEFAULT_VALUE);`
Try following source code it worked for me
//Fetching id from shared preferences
SharedPreferences sharedPreferences;
sharedPreferences =getSharedPreferences(Constant.SHARED_PREF_NAME, Context.MODE_PRIVATE);
getUserLogin = sharedPreferences.getString(Constant.ID_SHARED_PREF, "");

Categories

Resources