Editing SharedPreferences with Android KTX

Jetpack includes the Android KTX foundation library. Android KTX is a set of Kotlin extensions that allows you to leverage Kotlin language features when writing code that relies on Android APIs written in Java. Using Android KTX does not change the functionality of the existing Java APIs. But it does help you keep your Kotlin code idiomatic.

As of this writing, Android KTX only includes extensions for a subset of Android Java APIs. See the Android KTX documentation (developer.android.com/​kotlin/​ktx) for a list of available extension modules. However, the core Android KTX module does include an extension for editing shared preferences.

Update QueryPreferences to use Android KTX. First, add the core Android KTX dependency to your app module’s build.gradle file.

Listing 26.17  Adding core-ktx dependency (app/build.gradle)

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation"org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.core:core-ktx:1.0.0'
    ...
}

Next, update QueryPreferences.setStoredQuery(…) to use Android KTX.

Listing 26.18  Using Android KTX (QueryPreferences.kt)

object QueryPreferences {
    ...
    fun setStoredQuery(context: Context, query: String) {
        PreferenceManager.getDefaultSharedPreferences(context)
            .edit() {
            .putString(PREF_SEARCH_QUERY, query)
            .apply()
            }
    }
}

SharedPreferences.edit(commit: Boolean = false, action: Editor.() -> Unit) is an extension function in core-ktx. If your code has an error, check to make sure you added an import statement for androidx.core.content.edit.

You specify the edits you want to make in the lambda argument you pass to SharedPreferences.Editor. Here, you write a single string using android.content.SharedPreferences.Editor.putString(…).

You remove the explicit call to SharedPreferences.Editor.apply() because the edit extension function calls apply() for you by default. You can override this default behavior by passing true as an argument to the edit extension function. Doing so causes edit to call SharedPreferences.Editor.commit() instead of SharedPreferences.Editor.apply().

Run your app and ensure that the functionality of PhotoGallery was not affected. Your app should behave as it did before you made the Android KTX edits. But now your shared preferences code is a shade more idiomatic. Kotlin lovers, rejoice.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
44.192.247.185