-1

I have the following code in my onActivityForResult method after I add a contact using an intent.

  if (mySharedPrefs.getBoolean("settingsPopup", false) == false) { //First time

            new AlertDialog.Builder(this)
                    .setTitle("Go to settings? ")
                    .setMessage("POPUP")
                    .setNegativeButton("No", null)
                    .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {

                            Intent settingsIntent = new Intent(MainActivity.this, Settings.class);
                            startActivity(settingsIntent);

                        }
                    }).show();

            myEditor = mySharedPrefs.edit();
            myEditor.putBoolean("settingsPopup", true);
            myEditor.commit();

        }

I want this popup to only show once, which is why I set the shared preference key value "settingsPopup" to true after I first show the dialog. For some reason though, the dialog shows every time the onActivityForResult method gets called. Why does it show every time?

PS: I am using the same shared preference object for storing other values.

Edit

I initialize my shared prefs in onCreate like so:

mySharedPrefs = this.getSharedPreferences("sharedPrefsName", MainActivity.MODE_PRIVATE); //Making a shared preferences

Cœur
  • 37,241
  • 25
  • 195
  • 267
Ruchir Baronia
  • 7,406
  • 5
  • 48
  • 83
  • 1
    Why `== false`? Not-ing the getBoolean would look better – OneCricketeer Feb 06 '16 at 18:06
  • @cricket_007 In the beginning I simply had the statement with an `!` before it, but that didn't work, so I changed it in an effort to fix the issue. Still no luck though... – Ruchir Baronia Feb 06 '16 at 18:07
  • 1
    Well, yeah, it's doing the same thing as what you have, I was just pointing out an unnecessary equals sign :) – OneCricketeer Feb 06 '16 at 18:09
  • @cricket_007 Thats cool, thanks! Do you know what might be the problem in this code? Thanks cricket! :) – Ruchir Baronia Feb 06 '16 at 18:10
  • 1
    Yup. Anyways, yes, can you add more code to your question such as where you initialize your SharedPreferences. And do you want to only ever show the popup once or only not show it when the user presses yes? – OneCricketeer Feb 06 '16 at 18:13
  • @cricket_007 I only want to show it once, regardless of what the user clicks. I initialize in `onCreate` like so: `mySharedPrefs = this.getSharedPreferences("sharedPrefsName", MainActivity.MODE_PRIVATE); //Making a shared preferences` – Ruchir Baronia Feb 06 '16 at 18:15
  • 1
    is this piece of code being called in a loop? – Viral Patel Feb 06 '16 at 18:23
  • @AndroidMechanic No, it is in my `onActivityForResult` method which gets called after I pick a contact. – Ruchir Baronia Feb 06 '16 at 18:24
  • 1
    code looks sane. can you just clear the data from `app info` screen and try again? probably the preference file got corrupted. or just try using a different name for your prefs file. – Viral Patel Feb 06 '16 at 18:30
  • 1
    boolean result = mEditor.apply (); check this boolean. – Hiren Patel Feb 06 '16 at 18:33
  • @AndroidMechanic It's still not working after I cleared the data. What do you mean by change the name for my prefs file? – Ruchir Baronia Feb 06 '16 at 18:33
  • 1
    i meant : change to this `mySharedPrefs = this.getSharedPreferences("differentsharedPrefsName", 0);` – Viral Patel Feb 06 '16 at 18:36
  • @AndroidMechanic Tried both ways...still not working. – Ruchir Baronia Feb 06 '16 at 18:37
  • then i guess problem is somewhere else. can you share the full `onCreate` and `onActivityForResult`? – Viral Patel Feb 06 '16 at 18:39
  • also just add this class and try creating an instance of `SharedPreferencesHelper` [*code here*](https://github.com/viralypatel/Android-SharedPreferences-Helper/blob/master/library/src/main/java/com/viralypatel/sharedpreferenceshelper/lib/SharedPreferencesHelper.java) and remove the editor. – Viral Patel Feb 06 '16 at 18:42
  • 1
    @AndroidMechanic So I got it to work, but I don't know what I did wrong. When I used a different shared preference object for my popup, it worked. Before, I was using the same shared preference object that I was using in the class. Why cant I use the same shared preference object to store more than one key value pair? – Ruchir Baronia Feb 06 '16 at 18:46
  • 1
    @cricket_007 So I got it to work, but I don't know what I did wrong. When I used a different shared preference object for my popup, it worked. Before, I was using the same shared preference object that I was using in the class. Why cant I use the same shared preference object to store more than one key value pair? – Ruchir Baronia Feb 06 '16 at 18:47
  • Strange... I use the same instance always and works just fine. Need to try this thing at high speed probably. – Viral Patel Feb 06 '16 at 18:49
  • 1
    I think when you did `this.getSharedPrefreneces`, you were using it locally to that Activity, if you want to use a SharedPreferences app-wide, you need to declare it like a singleton – OneCricketeer Feb 06 '16 at 18:50
  • @cricket_007 So I cant store more than one value in a shared preference? – Ruchir Baronia Feb 06 '16 at 18:51
  • one more suggestion. with the same instance, can you write the pref value before showing the alert dialog (inside the if block, of course)? I'm feeling it is the alert dialog causing the problem. just in case. would be good to know if it works that way. – Viral Patel Feb 06 '16 at 18:51
  • You can. Who said you couldn't? You can't have multiple values for a single key – OneCricketeer Feb 06 '16 at 18:53
  • @cricket_007 Then why wasn't it working when I tried to add another value to my shared pref? – Ruchir Baronia Feb 06 '16 at 18:59
  • @cricket_007 http://stackoverflow.com/questions/35328936/why-is-this-value-null – Ruchir Baronia Feb 11 '16 at 01:06
  • Because you have to get the SharedPreferences from the application context instead of per activity or service – OneCricketeer Feb 11 '16 at 01:18
  • @cricket_007 Oh, then how do I get it from the application? Feel free to post an answer – Ruchir Baronia Feb 11 '16 at 01:19
  • It's already in that other post `getApplicationContext().getSharedPreferences` and you have to use the same string in the first parameter – OneCricketeer Feb 11 '16 at 02:15

3 Answers3

1

Create a class and call it SettingManager like following :

public class SettingsManager {
    public static final String DEFAULT_PREFERENCES_NAME = "defaultPreferences";

    public static final String PREFERENCE_FIRST_RUN = "isFirstRun";

    public static SharedPreferences getDefaultPreferences(Context context) {
        return context.getSharedPreferences(DEFAULT_PREFERENCES_NAME, Context.MODE_PRIVATE);
    }

    public static boolean isFirstRun(Context context) {
        SharedPreferences preferences = getDefaultPreferences(context);
        boolean isFirstRun = preferences.getBoolean(PREFERENCE_FIRST_RUN, true);
        preferences.edit().putBoolean(PREFERENCE_FIRST_RUN, false).commit();

        return isFirstRun;
    }

}

Then call it with something like this :

boolean isFirstRun = SettingManager.isFirstRun(getActivity());
Amir
  • 16,067
  • 10
  • 80
  • 119
  • Okay, thanks, but what is wrong with my way? Thanks so much Amir! – Ruchir Baronia Feb 06 '16 at 18:31
  • @RuchirBaronia I think you didn't get proper instance of **Preference**; pay attention to way How preferences works. also debugging is best way to understand what's happen – Amir Feb 06 '16 at 18:42
  • But why? I instanciate it in onCreate? Question is edited with instantiation. – Ruchir Baronia Feb 06 '16 at 18:43
  • So I got it to work, but I don't know what I did wrong. When I used a different shared preference object for my popup, it worked. Before, I was using the same shared preference object that I was using in the class. Why cant I use the same shared preference object to store more than one key value pair? – Ruchir Baronia Feb 06 '16 at 18:47
  • You can use same shared preferences as many as you like. just define another **PREFERENCE_FIRST_RUN** and define another **isFirstRun** – Amir Feb 06 '16 at 18:50
  • I usually do something like this with the [Application](https://developer.android.com/reference/android/app/Application.html) class since that is the base context for any app. – OneCricketeer Feb 06 '16 at 18:52
0

Try with putting code to store boolean variable before AlertDialog code:

if (mySharedPrefs.getBoolean("settingsPopup", false) == false) { //First time
            myEditor = mySharedPrefs.edit();
            myEditor.putBoolean("settingsPopup", true);
            myEditor.commit();

            new AlertDialog.Builder(this)
                    .setTitle("Go to settings? ")
                    .setMessage("POPUP")
                    .setNegativeButton("No", null)
                    .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {

                            Intent settingsIntent = new Intent(MainActivity.this, Settings.class);
                            startActivity(settingsIntent);

                        }
                    }).show();


        }
Rohit Sharma
  • 2,017
  • 1
  • 20
  • 22
  • Okay, I did that, but it still isn't working. What else could the problem be – Ruchir Baronia Feb 06 '16 at 18:04
  • 1
    An AlertDialog doesn't block any code from executing, it runs on a separate thread – OneCricketeer Feb 06 '16 at 18:10
  • can you post the code where you created shared preference object? – Rohit Sharma Feb 06 '16 at 18:10
  • In onCreate: `mySharedPrefs = this.getSharedPreferences("sharedPrefsName", MainActivity.MODE_PRIVATE); //Making a shared preferences` – Ruchir Baronia Feb 06 '16 at 18:15
  • So I got it to work, but I don't know what I did wrong. When I used a different shared preference object for my popup, it worked. Before, I was using the same shared preference object that I was using in the class. Why cant I use the same shared preference object to store more than one key value pair? – Ruchir Baronia Feb 06 '16 at 18:47
0

Try using apply() instead. Apply will update the preference object instantly and will save the new values asynchronously, so allowing you to read the latest values.

According to the 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. If another editor on this SharedPreferences does a regular commit() while a apply() is still outstanding, the commit() will block until all async commits are completed as well as the commit itself.

It goes on to say:

As SharedPreferences instances are singletons within a process, it's safe to replace any instance of commit() with apply() if you were already ignoring the return value.

Austin
  • 8,018
  • 2
  • 31
  • 37
  • Hey, I tried `apply()`, but it still doesn't work. I have edited my question with more code including the code where I initialize the prefs. – Ruchir Baronia Feb 06 '16 at 18:20
  • So I got it to work, but I don't know what I did wrong. When I used a different shared preference object for my popup, it worked. Before, I was using the same shared preference object that I was using in the class. Why cant I use the same shared preference object to store more than one key value pair? – Ruchir Baronia Feb 06 '16 at 18:47