Android- deprecated method warning regarding PreferenceActivity

jillianjiggs picture jillianjiggs · Feb 7, 2013 · Viewed 27.7k times · Source

When I attempt to follow Android's Developer guides and tutorials for creating a Settings Activity using Preferences, I receive warnings such as:

"The method addPreferencesFromResource(int) from the type PreferenceActivity is deprecated"

for both of these lines in the code:

getPreferenceManager().setSharedPreferencesName(PREFS_NAME);
addPreferencesFromResource(R.xml.default_values);

I know these are just warnings, but I was wondering if they will cause any issues, now or in the future, when I am running the application that I am designing.

public class DefaultValues extends PreferenceActivity {

    static final String PREFS_NAME = "defaults";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getPrefs(this);
        getPreferenceManager().setSharedPreferencesName(PREFS_NAME);
        addPreferencesFromResource(R.xml.default_values);
    }

    static SharedPreferences getPrefs(Context context) {
        PreferenceManager.setDefaultValues(context, PREFS_NAME, MODE_PRIVATE,
                R.xml.default_values, false);
        return context.getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
    }
}

Answer

Cristan picture Cristan · Jul 3, 2018

PreferenceActivity() is deprecated, but PreferenceFragment() is now as well. PreferenceFragmentCompat() is now the way to go:

Add dependency

implementation "androidx.preference:preference:1.1.1"

Or in case you are still using the support library:

implementation "com.android.support:preference-v7:28.0.0"

Extend PreferenceFragmentCompat

class MyPreferenceFragment : PreferenceFragmentCompat() {
    override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
        addPreferencesFromResource(R.xml.app_preferences)
    }
}

Show your Fragment

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    supportFragmentManager.beginTransaction().replace(android.R.id.content, MyPreferenceFragment()).commit()
}

Specify preferenceTheme

In your AppTheme, add either of the following preference themes, depending of which one you think looks better:

<item name="preferenceTheme">@style/PreferenceThemeOverlay</item>
<item name="preferenceTheme">@style/PreferenceThemeOverlay.v14.Material</item>