Search code examples
androidandroid-fragmentsandroid-preferences

NotificationPreferenceFragment - default constructor is deprecated


My code is:

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static class NotificationPreferenceFragment extends PreferenceFragment {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.pref_notification);
        setHasOptionsMenu(true);
        bindPreferenceSummaryToValue(findPreference("notifications_new_message_ringtone"));
        Preference notificationPref = findPreference("notifications_new_message");
        notificationPref.setOnPreferenceChangeListener((preference, newValue) -> {
            boolean isNotificationOn = (Boolean) newValue;
            if(preference.getKey().equals("notifications_new_message") && isNotificationOn){
                FirebaseMessaging.getInstance().subscribeToTopic("news");
            }else{
                FirebaseMessaging.getInstance().unsubscribeFromTopic("news");
            }
            return true;
        });

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == android.R.id.home) {
            startActivity(new Intent(getActivity(), ActivityPref.class));
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

Android Studio report that default constructor of NotificationPreferenceFragment is deprecated. How to fix deprecated warning?


Solution

  • Use the AndroidX Preference Library. This library manages the user interface and interacts with storage so that you define only the individual settings that the user can configure.

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

    For more detail: Follow this link