Showing posts from February, 2021

Store Key Value Pairs Using Jetpack Data Store

One of the ways we can store information on an Android device is by using Shared Preferences. These Shared Preferences help us save key-value pairs. A newer way of saving such key-value pairs is using the Jetpack library Data Store . The Data Store library saves the key-value pairs using coroutine blocks and provides the ability to read the saved preferences using the collect function available in the Kotlin Flow. In this article, we will take a look at the Data Store class available in the Jetpack library and how to save, read the data using it. The first thing we need to do is add the dependency in the module level build.gradle file. implementation "androidx.datastore:datastore-preferences:1.0.0-alpha06" Create an instance of the Data Store using context and by passing the file name to the createDataStore function. Android creates the data store file inside a folder named datastore and this folder will be available in the app's files directory. The name passed to th

Use Java8 APIs on Older Android Versions

The less adoption of Java8 APIs in the Android Codebase is because of the lack of support on the older versions. Even though Java8 was released in 2014, it took a while for Google to resolve the issue. Existing Issue We will take an example to understand the issue in detail. Let's say we have an array list that contains countries and we need to check if the desired country is available in the list. The code to achieve it would look something like below. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { // Find the country with name India val country = { it == "India" }.findFirst() if (country.isPresent) { // Country is present in the list } else { // Country is not present in the list } } else { // For loop to filter and find the item on the older version var countryPresent = false countryArrayList.forEach { if (it == "India") { // Country is present in t