Search code examples
javaandroidandroid-fragmentsandroidxandroid-preferences

PreferenceFragmentCompat Fragment has mPreferenceManager null during activity OnCreate after inflating


I can't quite figure out this. I set a breakpoint in the code on the library for onCreate(@Nullable Bundle savedInstanceState) method of the library and it's like it's not called.

My fragment code is super simple

public class MySettingsFragment extends PreferenceFragmentCompat {
    @Override
    public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
        setPreferencesFromResource(R.xml.preferences, rootKey);
    }
}

And my activity is not that big too

public class PreferencesActivity extends AppCompatActivity
{
    MySettingsFragment frag;

    @SuppressWarnings("unused")
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.settings_activity);

        frag = new MySettingsFragment();

        getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.settings_container, frag)
                .commit();
                
        // frag has null mPreferenceManager here
        // so some stuff I call from it will crash
    }

    // ...    
}

I can see and load my settings on the app, but I wanted to pickup frag there and read stuff like frag.getPreferenceScreen(); or frag.findPreference(PREFERENCE_UID) but frag has a null mPreferenceManager so most things fail.

I need to read these since I am syncing some settings from my App with the Native parts and most Preferences tutorials are too simple. Any idea why mPreferenceManager is null in my fragment during the Activity OnCreate?


Solution

  • I found out that mPreferenceManager is not null on the Fragment's own onCreate method, so I moved the things I wanted to run on the Activity's onCreate method to there.