javaandroidandroid-studiosharedpreferencesis-empty

Android Java: SharedPreferences being set but not being read


My app creates a default SharedPrferences for a "default font size" (specifically: public static final String DEFAULT_FONT_SIZE_KEY = "defaultFontSize"; in my AppUtils class) when the app opens. It seems I am able to create this SharedPreferences with default value of 16 and immediately after creating I try to dump all the value keys and nothing is returned. At this point in the code I have not implemented nor adjusted the value of the font size key, only the first steps - creation and immediately checking via a dump of whether it is stored. After creating nothing is returned in the dump.

The app android.intent.action.MAIN is the WelcomeActivity class. In this class I declare SharedPreferences and then initialize with a method call to AppUtils.initializeSharedPreferences in onCreate:

...
    private SharedPreferences sharedPreferences;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_welcome);

        AppUtils.initializeSharedPreferences(this);
        sharedPreferences = AppUtils.getSharedPreferences();
...

The method initializeSharedPreferences is only called one time and should be creating the DEFAULT_FONT_SIZE_KEY, thus creating a SharedPreference if none exists, here is that method which is in the AppUtils class:

    public static void initializeSharedPreferences(Context context) {
        if (sharedPreferences == null) {
            sharedPreferences = context.getSharedPreferences("SongTrackerApp", Context.MODE_PRIVATE);
            if (getDefaultFontSize(sharedPreferences) == 0) {
                saveDefaultFontSize(sharedPreferences, 16);
            }
            Log.d("AdjustTextSize", "(AppUtils) INIT: line #17, 1st Value-DEFAULT_FONT_SIZE_KEY: " + getDefaultFontSize(sharedPreferences));
        }
        Log.d("AdjustTextSize", "(AppUtils) INIT: line #19, DEFAULT_FONT_SIZE_KEY: " + getDefaultFontSize(sharedPreferences) + ", context: " + context);
    }

Also inside the onCreate within the WelcomeActivity class I get the value for the DEFAULT_FONT_SIZE_KEY and then call a method to dump all the SharedPreferences (see dbHelper.logSharedPreferencesEntries):

        // Get all key-value pairs from SharedPreferences
        if (sharedPreferences != null) {
            // Print out all sharedPreferences:
            Log.d("AdjustTextSize", "(WelcomeActivity) line #77, DEFAULT_FONT_SIZE_KEY: " + AppUtils.getDefaultFontSize(sharedPreferences));
            dbHelper.logSharedPreferencesEntries(sharedPreferences, "WelcomeActivity");
        }

The Log.d indicates that there is in fact a SharedPreferences for DEFAULT_FONT_SIZE_KEY:

(WelcomeActivity) line #77, DEFAULT_FONT_SIZE_KEY: 16.0

At this point in the code I am still in the Main activity and call a method in DatabaseHelper class (dbHelper.logSharedPreferencesEntries) to dump all the SharedPreferences however NOTHING is returned. Here is the method logSharedPreferencesEntries which returns 'true' for if (allEntries.isEmpty()) ...:

    public void logSharedPreferencesEntries(SharedPreferences sharedPreferences, String pageName) {
        Map<String, ?> allEntries = sharedPreferences.getAll();
        // Check if there are any entries
        if (allEntries.isEmpty()) {
            Log.d("AdjustTextSize", "(DBHelper via: " + pageName + ") DUMP line #1063 No sharedPreference keys found");
            return;
        }
        // Iterate through the entries and log them
        for (Map.Entry<String, ?> entry : allEntries.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();
            // Display constant name, key name, and value in Log.d
            String constantName = findConstantName(key);
            Log.d("AdjustTextSize", "(DBHelper via: " + pageName + ") DUMP line #1072 - Constant: " + constantName + ", Key: " + key + ", Value: " + value.toString());
        }
    }

I have researched other related entries within stackoverflow, although many related issues to SharedPreferences many are dated going back to 2012 - nothing recent seems to address my 2023 problem.

Thank you in advance for reviewing and commenting.

EDIT: 12.14.2023 In response to @ltp

Thank you @ltp I replaced editor.apply(); with editor.commit(); the latter your suggestion and which works synchronously thus I should be seeing the impact directly as opposed to the asynchronous apply(). Curious as I am setting a SharedPreferences in the initializeSharedPreferences method:

    public static void initializeSharedPreferences(Context context) {
        if (sharedPreferences == null) {
            sharedPreferences = context.getSharedPreferences("SongTrackerApp", Context.MODE_PRIVATE);
            if (getDefaultFontSize(sharedPreferences) == 0) {
                saveDefaultFontSize(sharedPreferences, 16);
            }
        }
    }

and next line of code after the call to initializeSharedPreferences is the method 'dumping' all SharedPreferences - even with commit() I still get the Log.d "No sharedPreference keys found" - and I know in the previous line it was set. If I change the text size using what I programmed into the app's code, after about 2-3 attempts I DO see the 'dump' method displaying Constant: DEFAULT_FONT_SIZE_KEY, Key: defaultFontSize, Value: 0.0 but the font size is not accurate, I believe that is a separate issue so will ignore for present. Curious about any other comments please!


Solution

  • If you are using SharedPreferences.Editor.apply(), replace it with SharedPreferences.Editor.commit(). Quoting from the doc:

    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