Listing 26.11 - deprecated PreferenceManager and getDefaultSharedPreferences

Hi,

after creating QueryPreferences.kt file android.preference.PreferenceManager is imported by default and Android Studio warns that PreferenceManager and getDefaultSharedPreferences are deprecated.

Here is the solution:

  1. add two dependencies to your gradle
implementation 'androidx.preference:preference-ktx:1.2.1'
implementation 'androidx.legacy:legacy-preference-v14:1.0.0'
  1. delete
    import android.preference.PreferenceManager
    add
    import androidx.preference.PreferenceManager

If you are facing “duplicate class” run-time error, you might also need to add these dependencies:

implementation "androidx.lifecycle:lifecycle-viewmodel:2.5.1"
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.5.1"
1 Like

This listing refers to the deprecation of PreferenceManager and getDefaultSharedPreferences in Android programming. These two classes were used to manage shared preferences in Android applications.

Shared preferences are used to store small amounts of data in an application, such as user preferences or settings. Previously, developers could use PreferenceManager to access the default shared preferences file for an application using getDefaultSharedPreferences.

However, with the release of Android 11, PreferenceManager and getDefaultSharedPreferences have been deprecated in favor of the new SharedPreferences API. This new API provides better performance and more flexibility in managing shared preferences.

Developers are now encouraged to use the getSharedPreferences method to access the shared preferences for an application instead of using PreferenceManager and getDefaultSharedPreferences. This allows for greater customization of shared preferences files and reduces the likelihood of naming conflicts with other applications.

In summary, while PreferenceManager and getDefaultSharedPreferences may still work in current Android versions, developers should migrate to using the SharedPreferences API to future-proof their applications and take advantage of the performance improvements and flexibility it offers.

Visit Exams4sure for more IT Certifications Questions and Answers.