0

So in my MainActivity i am using SharedPreferences when checking boolean values doing like this.

  public boolean uptadevalues(boolean updatedvalue) {

        SharedPreferences preferences = getPreferences(MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();


        if (mPremiumVQuery) {
            Log.d(TAG, "Called uptadevalues mPremiumVQuery");
            editor.putBoolean(mPremiumVString, true);
            editor.apply();
        } else {
            editor.putBoolean(mPremiumVString, false);
            editor.apply();
        }

        Log.d(TAG, "Called uptadevalues  ");

        return updatedvalue;
    }

I know that mPremiumQuery is true because Log.d(TAG, "Called uptadevalues mPremiumVQuery"); appears on the logcat. So that means that the SharedPreference should be Writing the preference.

On fragment:

    public boolean getPremiumValues() {

        Log.d(TAG, "getPremiumValues");
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
        return sp.getBoolean(mPremiumVString, false);

    }

and then on button click

 case R.id.button5:
                            if (getPremiumValues()) {
                            ** open activity **
                            } else {
                            **  dialog **  }

It is always showing the dialog but it realy should be opening the new activity. I can't see where is my error! Thanks for any help.

UPDATE:

The problem was that I was using different methods to access SharedPreferences as @piotr.wittchen said.

Has many said to change from commit(); to apply(); i tried and no diference its made and has it is recomended to use apply(); by google I stayed with it.

Rúben
  • 122
  • 2
  • 8

1 Answers1

2

Something is wrong with logic of your function or it's incomplete. First of all, You have spelling mistake in its name. It's uptadevalues, but probably should be updateValues. Secondly, you pass boolean updatedvalue, then you do nothing with this value and return it. It doesn't make any sense. In your first method, you are accessing SharedPreferences in the following way:

SharedPreferences preferences = getPreferences(MODE_PRIVATE);

but in the second method you are accessing them like that:

SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());

It's better to use the same method of accessing SharedPreferences in both cases. It may cause data inconsistency. Try to use only one instance of SharedPreferences. Currently, you are using many of them.

Piotr Wittchen
  • 3,853
  • 4
  • 26
  • 39
  • 1
    Thank you! you gave a good explanation of what my errors where. The problem was what you point out I was using different methods to access SharedPreferences what’s was giving me the error. – Rúben Mar 12 '15 at 21:55