SharedPreferences not working onResume - android

Got a problem with the Shared Preferences in Android - I want to be able to put some Strings (Save the IDs of a Picture) as favorite for the next launches - it works perfect, it recognizes if the ID is already inside the Shared Preferences and removes it if necessary, but when I stop the App by pressing the home button (without killing the app process) and then return to it, it doesn´t recognize it anymore. If I kill the process and restart the app, it works fine.
So here´s my code
MainActivity onCreate
preferences = getSharedPreferences("favo", MODE_PRIVATE);
edit = getSharedPreferences("favo", MODE_PRIVATE).edit();
MainActivity onResume
#Override
protected void onResume() {
preferences = getSharedPreferences("favo", MODE_PRIVATE);
edit = getSharedPreferences("favo", MODE_PRIVATE).edit();
super.onResume();
}
I´ve already tried to do it without onResume but it doesn´t change the result.
Method to change the Shared Preferences
if (checkTheSharedPreferences(numberFavo)){
v.setBackgroundResource(R.drawable.favo);
edit.putString(pref, pref);
edit.apply();
showIt = "Zu Favoriten hinzugefügt";
}else{
v.setBackgroundResource(R.drawable.favo2);
edit.remove(pref);
edit.apply();
showIt = "Aus Favoriten entfernt";
}
If my method to check if the SharedPreferences returns true it means that the String isn´t inside the SharedPrefs and can be added, otherwise it will be removed as the user wants to remove it from his favorites.
Method to check if the String is inside the Prefs
public Boolean checkTheSharedPreferences(int number) {
SharedPreferences preferences = getSharedPreferences("favo", MODE_PRIVATE);
Map<String, ?> map = preferences.getAll();
for (Map.Entry<String, ?> entry : map.entrySet()) {
if (entry.getValue().toString().equals(bilderIDs.get(number))) {
return false;
}
}
return true;
}
As mentioned above, it works perfect, unless the App gets invisible/into the background and is opened again without a restart.
Thanks in advance
EDIT
Seems like it works if I wait for about 30 seconds after onResume is called, but that´s not really a possibility to wait for so long as it is on the UI Thread and the User might presses the button to remove/add the SharedPref within the 30 seconds

SharedPreferences.Editor.apply() is a async method.It will store values in other thread.SharedPreferences.Editor.commit() is a sync method.
if (checkTheSharedPreferences(numberFavo)){
v.setBackgroundResource(R.drawable.favo);
edit.putBoolean("myfav" + numberFavo, true);
edit.commit();
showIt = "Zu Favoriten hinzugefügt";
}else{
v.setBackgroundResource(R.drawable.favo2);
edit.remove("myfav" + numberFavo);
edit.commit();
showIt = "Aus Favoriten entfernt";
}
public Boolean checkTheSharedPreferences(int number) {
SharedPreferences preferences = getSharedPreferences("favo", MODE_PRIVATE);
return preferences.getBoolean("myfav" + number,false);
}
#Override
protected void onResume() {
super.onResume();
preferences = getSharedPreferences("favo", MODE_PRIVATE);
edit = getSharedPreferences("favo", MODE_PRIVATE).edit();
}

Related

SharedPreferences saves state between android activities but not upon restarting the app

I'm running to a really weird behavior with SharedPreferences. I'm wondering if I'm running into a synchronization issue.
It seems like the app can remember the preference changes in between activities but not when I restart the app. The state always returns back to the very first instance I created a preference. I've followed several examples, tutorials, and android documentation that all suggest similar code layout. I also watched how the preference.xml file changed while interacting with my code using the debugger and I confirmed it looked like the key value pair updated.
Could I be experiencing a synchronization issue with my emulator? I tried using both the editor.apply() method and editor.commit() method with the same results.
The only thing I've found that fixes my problem is using the editor.clear() method, but this feels a bit hacky...
note: please forgive the variable names, I'm making a pokedex...
public class SecondActivity extends AppCompatActivity {
private boolean caught;
private Set<String> pokemonCaught;
private String pokemonName;
public SharedPreferences sharedPreferences;
public static final String SHARED_PREFERENCES = "shared_preferences";
public static final String PREF_KEY = "inCaughtState";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
/*SKIPPING THE VIEW SETUP*/
/*SKIPPING BUTTON VIEW ATTRIBUTES*/
//variables required for changing button state
pokemonName = (String) nameTextView.getText();
caught = false;
//Loading in sharedPreferences
sharedPreferences =
getSharedPreferences(SHARED_PREFERENCES, Context.MODE_PRIVATE);
pokemonCaught = sharedPreferences.getStringSet(PREF_KEY, new HashSet<String>());
if (pokemonCaught.contains(pokemonName)) {
toggleCatch(catchButton);
}
}
public void toggleCatch (View view) {
//Editing and updating preferences
sharedPreferences =
getSharedPreferences(SHARED_PREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
if (caught == true) {
/*SKIPPING BUTTON ATTRIBUTES*/
caught = false;
pokemonCaught.remove(pokemonName);
}
else {
/*SKIPPING BUTTON ATTRIBUTES*/
caught = true;
pokemonCaught.add(pokemonName);
}
editor.clear(); //This is my hacky solution...
editor.putStringSet(PREF_KEY, pokemonCaught);
editor.apply();
}
}
Try to use SharedPreferences this way:
To save data
SharedPreferences.Editor editor = getSharedPreferences("PREFS", MODE_PRIVATE).edit();
editor.putString("stringName", "stringValue");
editor.apply();
To retrieve data
SharedPreferences preferences = getApplicationContext().getSharedPreferences("PREFS", MODE_PRIVATE);
String name = preferences.getString("stringName", "none"));
Note that this "none" is in case to string "stringName" be null.

unable to clear my sharedPreferences using editor.clear().commit();

I am working on an android project where I have a scenario such as :
I used place picker.and data that place picker gave is sent to different activities using shared preference.and show this data in TextView.
but the problem is when I closed activity and again open that activity; my data still visible in TextView.
even when I cleared it in onDestroy().
here is my code for send data :
SharedPreferences settings = getSharedPreferences("address", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString("address", (String) Address);
editor.commit();
finish();
here is my code to set and clear data:
#Override
protected void onResume() {
super.onResume();
SharedPreferences settings = getSharedPreferences("address", Context.MODE_PRIVATE);
String n = settings.getString("name", "");
String a = settings.getString("address", "");
name.setText(n);
location.setText(a);
}
#Override
protected void onDestroy() {
SharedPreferences settings = getSharedPreferences("address", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.remove("address");
editor.clear().commit();
super.onDestroy();
}
here is my preference manager class :
public class PrefManager {
SharedPreferences pref;
SharedPreferences.Editor editor;
Context _context;
// shared pref mode
int PRIVATE_MODE = 0;
// Shared preferences file name
private static final String PREF_NAME = "sara";
private static final String IS_FIRST_TIME_LAUNCH = "IsFirstTimeLaunch";
public PrefManager(Context context) {
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
public void setFirstTimeLaunch(boolean isFirstTime) {
editor.putBoolean(IS_FIRST_TIME_LAUNCH, isFirstTime);
editor.clear().commit();
}
public boolean isFirstTimeLaunch() {
return pref.getBoolean(IS_FIRST_TIME_LAUNCH, true);
}
}
And please don't mark this question as duplicate because I see every related questions and see answers. I tried every possible solutions but nothing worked for me. I am new to android so please help me.
I'm not sure where you are using SharedPreference object to set data in it. But I guess this is the problem:
In this activity, you are clearing SharedPreferenece correctly.
You go back to previous Activity. And the previous activity, sets data to shared preference, again. So SharedPreference is not empty anymore.
You go to second activity (which you remove shared preference data in onDestroy()). As shared preference is not empty, you are seeing data again.
So check the code again and feel free to ask any questions.
Try check the logs to make sure you are really going 'onDestory' well.
#Override
protected void onDestroy() {
Log.d("address", "onDestory");
SharedPreferences settings = getSharedPreferences("address", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.remove("address");
editor.clear().commit();
super.onDestroy();
}
There is no problem with the code for creating and removing SharedPreferences.

Google signin - Need to permanently save user details on exit

I have integrated Google sign in sample application with my applications Main Activity.
I have a button in my Navigation header to launch login activity.
When I login with my google account, it fetches my name and email Id into Navigation Header.
Now the issue is, if I quit this app, I need to sign in again every time. How can I save the login details.
I have gone through multiple articles which talk about Shared Preference, however shared preference doesn't work for me.
Below is one of the code snippet I have tried. I am calling storeUserDetails() in onBackPressed and getUserDetails() in onCreate().
public void storeUserDetails(String userName, String emailID){
mSharedPreference = getSharedPreferences("userDetails",MODE_PRIVATE);
SharedPreferences.Editor mEditor = mSharedPreference.edit();
mEditor.putString("userFullName",userName);
mEditor.putString("userEmailID",emailID);
mEditor.apply();
}
private String getUserDetails(){
mSharedPreference = getSharedPreferences("userDetails",MODE_PRIVATE);
return mSharedPreference.getString("userFullName","#gmail.com");
}
Tried this tutorial as well
https://www.tutorialspoint.com/android/android_shared_preferences.htm
//First instantiate sharedpreferences
SharedPreferences sharedpreferences;
sharedpreferences=getSharedPreferences(MyPREFERENCES,Context.MODE_PRIVATE);
private String name,phone,email;
//OnPause method to save shared preferences when activity is destroyed
#Override
public void onPause() {
super.onPause(); // Always call the superclass method first
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Name, name);
editor.putString(Phone, phone);
editor.putString(Email, email);
editor.commit();
}
//OnResume method used to retrieve sharedpreferences
#Override
public void onResume() {
super.onResume(); // Always call the superclass method first
SharedPreferences prefs = this.getSharedPreferences("MyPREFERENCES", Context.MODE_PRIVATE);
name = prefs.getString("Name","");
phone = prefs.getString("Phone","");
email = prefs.getString("Email","");
}
Also to handle the login issue, you could use your launcher activity and sharedpreferences to check if Name is null, if it isn't then navigate to your mainactivity, and if it is then navigate to login, then on your logout function just make sure you clear the sharedpreferences.

How to launch settings on the first run of the app

I have developed an Android app and it run effectively though I want launch the settings activity on the every first run (after installation) then for the rest of its life cycle, it should launch the main activity. How do I go about that?
Simply check the existing settings and launch the settings activity if they do not exist (files missing or shared preferences are not defined). Or, define a preference like FIRST_RUN with the default value true that you set to false on the first run.
See Android storage options on how to remember settings on Android.
Set it as the MainActivity and create a Shared Preference so it wont load every time the Application loads..
MainActivity
private final String KEY = "SHARED_KEY_FIRST_RUN";
public void onCreate() {
SharedPreferences pref = this.getSharedPrefereneces(....,Context.MODE_PRIVATE);
if(pref.getInteger(KEY,0) == 0) {
//Do first Time Loading.
}
else {
Intent intent = Intent(this,SecondActivity.class);
startActivity(intent);
}
}
dont forget to declare the SecondActivity in the Mainfest and save the Key with SharedPreferences.Editor
try this :
private boolean isFirstTime()
{
preferences = getPreferences(MODE_PRIVATE);
ranBefore = preferences.getBoolean("RanBefore", false);
if (!ranBefore) {
// first time
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("RanBefore", true);
editor.commit();
}
return !ranBefore;
}
So, if you want to check:
if (isFirstTime()){
//if first time do something
}

Shared Preferences not persistent after app restart

I found all answers here and tried all solutions, still my shared prefs are not persistent.
Here's my code:
public static void setActivated(boolean activated) {
SharedPreferences sp = Utils.getContext().getSharedPreferences(
USER_PREFS, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putBoolean(ASD, activated);
editor.commit();
}
public static boolean isActivated() {
SharedPreferences sp = Utils.getContext().getSharedPreferences(USER_PREFS, Context.MODE_PRIVATE);
return sp.getBoolean(ASD, true);
}
I've tried also:
editor.clear();
editor.put ..
editor.commit();
I've also tried with
editor.apply();
I even tried with both .apply() and .commit() and no luck.
Another idea was to try using a different mode for the files:
...getSharedPreferences(USER_PREFS, Context.MODE_MULTI_PROCESS);
The problem is that the values saved are not persistent. If I close the app and then re-open it the values are all wrong.
Does anyone have any ideas? I would also mention that the problem is only on some devices, for example HTC One S, Samsung Galaxy S3 (I tested on a different S3 and it worked perfectly).
EDIT: I call the save on a button click listener and I call isActivated when I load the fragment (after onViewCreated()).
Thanks!
Hi I think it should work. If clearing does not work, you could try the second option as detailed in my solution:
You have 2 options:
Get shared preference value during the life-cycle of the activity.
Call .clear before .commit
See my answer:
Android Persistent Checkable Menu in Custom Widget After Reboot Android
public abstract SharedPreferences.Editor clear()
Added in API level 1 Mark in the editor to remove all values from the
preferences. Once commit is called, the only remaining preferences
will be any that you have defined in this editor. Note that when
committing back to the preferences, the clear is done first,
regardless of whether you called clear before or after put methods on
this editor.
Returns Returns a reference to the same Editor object, so you can
chain put calls together.
In my user preferences class I was getting a null value on some other strings and my code was something like this:
SharedPreferences sp = Utils.getContext()
.getSharedPreferences(USER_PREFS, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
if (session != null && !"".equals(session)) {
sessionId = session;
editor.putString(SESSION, sessionId).commit();
} else {
sessionId = null;
editor.clear().commit();
}
The editor.clear() was resetting all my other commits!
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;
}
}

Categories

Resources