Blog Infos
Author
Published
Topics
Published
Topics

Android Jetpack to the Space

What is Datastore?
Implementing Preference DataStore
// For preference Datastore 
   implementation "androidx.datastore:datastore-preferences:1.0.0"

Some additional dependencies that one might need will be:

//For Coroutines if not added earlier
  implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.6.4'

//For lifecycle if not added earlier
  implementation "androidx.lifecycle:lifecycle-runtime-ktx:2.2.0-alpha02"
  implementation "androidx.lifecycle:lifecycle-livedata-ktx:2.2.0-alpha02"
Code Implementation

This will be our file structure. Naming it “Local”, to store it locally in our device.

 

package com.example.datastoretest.data.local
import androidx.datastore.preferences.core.Preferences
import kotlinx.coroutines.flow.Flow
interface IPreferenceDataStoreAPI {
suspend fun <T> getPreference(key: Preferences.Key<T>,defaultValue: T):Flow<T>
suspend fun <T> getFirstPreference(key: Preferences.Key<T>,defaultValue: T):T
suspend fun <T> putPreference(key: Preferences.Key<T>,value:T)
suspend fun <T> removePreference(key: Preferences.Key<T>)
suspend fun <T> clearAllPreference()
}
suspend fun <T> getPreference(key: Preferences.Key<T>,defaultValue: T):Flow<T>
 
suspend fun <T> getFirstPreference(key: Preferences.Key<T>,defaultValue: T):T
Object PreferenceDataStoreConstants
val name: String = "Android Dev"

Rather we write it as:

val STRING_KEY = stringPreferencesKey("STRING_KEY")

We concatenate the datatype in all small ahead of “PreferenceKey()”, like (“name_of_variable”), (“name_of_variable”), etc.

package com.example.datastoretest.data.local
import androidx.datastore.preferences.core.booleanPreferencesKey
import androidx.datastore.preferences.core.intPreferencesKey
import androidx.datastore.preferences.core.longPreferencesKey
import androidx.datastore.preferences.core.stringPreferencesKey
object PreferenceDataStoreConstants {
val IS_MINOR_KEY = booleanPreferencesKey("IS_MINOR_KEY")
val AGE_KEY = intPreferencesKey("AGE_KEY")
val NAME_KEY = stringPreferencesKey("NAME_KEY")
val MOBILE_NUMBER = longPreferencesKey("MOBILE_NUMBER")
}

Job Offers

Job Offers

There are currently no vacancies.

OUR VIDEO RECOMMENDATION

Jobs

Class PreferenceDataStoreHelper
private val Context.dataStore by preferencesDataStore(
    name = "PreferenceDataStore"
)
package com.example.datastoretest.data.local
import android.content.Context
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.emptyPreferences
import androidx.datastore.preferences.preferencesDataStore
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
import java.io.IOException
// Declaring/Creating the DataStore File for Application
private val Context.dataStore by preferencesDataStore(
name = "PreferenceDataStore"
)
class PreferenceDataStoreHelper(context: Context):IPreferenceDataStoreAPI {
// dataSource access the DataStore file and does the manipulation based on our requirements.
private val dataSource = context.dataStore
/* This returns us a flow of data from DataStore.
Basically as soon we update the value in Datastore,
the values returned by it also changes. */
override suspend fun <T> getPreference(key: Preferences.Key<T>, defaultValue: T):
Flow<T> = dataSource.data.catch { exception ->
if (exception is IOException){
emit(emptyPreferences())
}else{
throw exception
}
}.map { preferences->
val result = preferences[key]?: defaultValue
result
}
/* This returns the last saved value of the key. If we change the value,
it wont effect the values produced by this function */
override suspend fun <T> getFirstPreference(key: Preferences.Key<T>, defaultValue: T) :
T = dataSource.data.first()[key] ?: defaultValue
// This Sets the value based on the value passed in value parameter.
override suspend fun <T> putPreference(key: Preferences.Key<T>, value: T) {
dataSource.edit { preferences ->
preferences[key] = value
}
}
// This Function removes the Key Value pair from the datastore, hereby removing it completely.
override suspend fun <T> removePreference(key: Preferences.Key<T>) {
dataSource.edit { preferences ->
preferences.remove(key)
}
}
// This function clears the entire Preference Datastore.
override suspend fun <T> clearAllPreference() {
dataSource.edit { preferences ->
preferences.clear()
}
}
}
Implementing it to Store/Retrieve Data.
// Retriving Using the Flow Method
viewModelScope.launch {
preferenceDataStoreHelper.getPreference(NAME_KEY,"").collect {
name = it
}
}
// Retriving Using the Not Flow / static data Method
viewModelScope.launch {
val name = preferenceDataStoreHelper.getFirstPreference(NAME_KEY,"")
}
// Setting Data
val name = "Android Developer"
viewModelScope.launch {
preferenceDataStoreHelper.putPreference(NAME_KEY,name)
}
view raw ViewModel.kt hosted with ❤ by GitHub

ViewModel Implementation Demo

 

// Retriving Using the Flow Method
lifecycleScope.launch {
preferenceDataStoreHelper.getPreference(NAME_KEY,"").collect {
name = it
}
}
// Retriving Using the Not Flow / static data Method
lifecycleScope.launch {
val name = preferenceDataStoreHelper.getFirstPreference(NAME_KEY,"")
}
// Setting Data
val name = "Android Developer"
lifecycleScope.launch {
preferenceDataStoreHelper.putPreference(NAME_KEY,name)
}
view raw MainActivity.kt hosted with ❤ by GitHub

Activity Implementation Demo

 

This article was originally published on proandroiddev.com on December 29, 2022

YOU MAY BE INTERESTED IN

YOU MAY BE INTERESTED IN

blog
Data persistence is a very important aspect of app development. It could make or…
READ MORE

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Menu