0

I'm using an activity called SettingsActivity that extends PreferenceFragmentCompat. When the application starts for the very first time MainActivity, I try to get the preferences through getDefaultSharedPreferences(getApplicationContext()) but without success because they are only loaded when I start the Settings activity.

To prove this, I checked the file shared_preferences.xml and it's filled only when I open the SettingsActivity.

In this sense, how can I force the loading of the preferences in the MainActivity?

MainActivity

public class MainActivity extends AppCompatActivity {
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Map<String, ?> allPreferences = getDefaultSharedPreferences(MainActivity.applicationContext).getAll();
        Log.d(Class.forName(), allPreferences.isEmpty()); //prints true

        Intent intent_settings = new Intent(activityContext, SettingsActivity.class);
        startActivity(intent_settings);
     }
}

SettingsActivity

public class SettingsActivity extends PreferenceFragmentCompat {
    public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_settings);

        setPreferencesFromResource(R.xml.preferences, rootKey);

        Map<String, ?> allPreferences = getPreferenceManager().getSharedPreferences().getAll();
        Log.d(Class.forName, allPreference.isEmpty()); // prints false
    }
}
Alfabrick12
  • 5
  • 1
  • 5
  • 1
    Can you share the code? If you try to get a preference through the key, and it doesn't exist yet, there is a default value. – bytesculptor Mar 27 '20 at 19:46
  • @romulus I shared the code now. – Alfabrick12 Mar 27 '20 at 20:11
  • The accepted answer uses a deprecated class. See: https://stackoverflow.com/questions/56833657/preferencemanager-getdefaultsharedpreferences-deprecated-in-android-q/56911496 – hadasnah Jan 02 '22 at 22:56

1 Answers1

0

In your activity's onCreate place the following code

PreferenceManager.setDefaultValues(this, R.xml.preferences, false);

reference Android Developers Docs

Forntoh
  • 311
  • 4
  • 7