Henrique
Henrique

Reputation: 65

SharedPreferences does not return the default value

I have a sharedpreferences and I have created a method for it to be checked if it is the user's first time in the app. But it always returns the opposite of the default value.

My code:

public static Boolean getFirstOnApp(Context context) {
    SharedPreferences pref =  context.getSharedPreferences(LOGIN_PREFS_NAME, Context.MODE_PRIVATE);
    return pref.getBoolean(KEY_FIRST_TIME_ON_APP, true);
}

Is always returns false.

I call it on my controller:

 if (SaveSharedPreferences.getFirstOnApp(context)) {
            fabAtivaMapeamento.performClick();
            SaveSharedPreferences.setFirstOnApp(context, false);
        }

SaveSharedPreferences.setFirstOnApp(context, false); has never been called before. It is only changed within this If

I already uninstalled the app, forced it to stop, cleared data and cache.

How to solve?

Upvotes: 0

Views: 59

Answers (2)

Chrisvin Jem
Chrisvin Jem

Reputation: 4060

Edit - Check if the following works.

public static Boolean getFirstOnApp(Context context) {
    SharedPreferences pref =  context.getSharedPreferences(LOGIN_PREFS_NAME, Context.MODE_PRIVATE);
    //Check if the shared preference key exists.
    //This way, you can determine if the fault is here or elsewhere.
    if (pref.contains(KEY_FIRST_TIME_ON_APP)) {
        return pref.getBoolean(KEY_FIRST_TIME_ON_APP, true);
    } else {
        return true;
    }
}


Check if you've set your application to allow backup in the manifest android:allowBackup="true". Set it as false, uninstall and then reinstall the app.

android:allowBackup=“false”

In case that doesn't fix the issue, then try setting the following in your manifest, uninstalling the app and then reinstalling it.

android:fullBackupContent="false"

Upvotes: 1

Jimale Abdi
Jimale Abdi

Reputation: 2844

use like this to check if it's first time or not

SharedPreferences pref = getSharedPreferences(LOGIN_PREFS_NAME, Context.MODE_PRIVATE);
        if (pref.getBoolean(KEY_FIRST_TIME_ON_APP, false)) {

           //in here it's not for first time

        } else {

             //in here it's first time
        }

Upvotes: 1

Related Questions