Search code examples
androidandroid-studiosharedpreferences

Android - Strange behavior shared preferences after API 29


I upgraded my app from API 28 to 29. Tested its debug and release version. Everything works fine. However after publishing in the play store, the apps behaves weirdly.

Problem: It seems the default values for shared preferences are not correct.

I can't find any notes inside googles developer information for android 10.

Code:

Inside Activity

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
String birthdaysKey = "app.birthdays";
birthdays = prefs.getBoolean(birthdaysKey, false);

Inside XML

<SwitchPreferenceCompat
android:defaultValue="false"
app:icon="@drawable/ic_birthday_24dp"
app:key="app.birthdays"
app:summary="@string/birthday_description"
app:title="@string/birthday"
app:useSimpleSummaryProvider="false" />

buildgradle

implementation 'androidx.preference:preference:1.1.1'

The initial value is always true, but should be false.


Solution

  • I managed to find the following information:

    1. The xml declaration should be:

    <androidx.preference.PreferenceScreen ... and <androidx.preference.SwitchPreference ...

    1. It seems that getDefaultSharedPreferences(Context context) is no longer supported (neither for AndroidX)

    The problem I am facing is: How to use a preference screen without the default preference manager? There is no other way to read the data afaik.

    Solution:

    Disable AutoUpdate inside the manifest. This fixes the issue.