Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Jetpack DataStore implementation

Hello i am trying to implement JetPack datastore into my app by watching some tutorial i am newbie to koltin.
I followed everything in this video : https://www.youtube.com/watch?v=0J5GXuGD61E&t=366s

UserManager.kt

class UserManager(context: Context) {

//Create the dataStore
private val dataStore = context.createDataStore(name = "user_prefs")

//Create some keys
companion object {
    val USER_AGE_KEY = preferencesKey<String>("USER_AGE")
    val USER_NAME_KEY = preferencesKey<String>("USER_NAME")
}

//Store user data
suspend fun storeUser(age: String, name: String) {
    dataStore.edit {
        it[USER_AGE_KEY] = age
        it[USER_NAME_KEY] = name

    }
}

//Create a name flow
val userNameFlow: Flow<String> = dataStore.data.map {
    it[USER_NAME_KEY] ?: ""
}
//Create a name flow
val userAgeFlow: Flow<String> = dataStore.data.map {
    it[USER_AGE_KEY] ?: ""
}

}

Class MainActivity.kt

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class MainActivity : AppCompatActivity() {

lateinit var userManager: UserManager
var name = ""
var age = ""

var dataStoreEmail = ""
var dataStorePassword = ""

private fun saveData(email: String, password:String){
    GlobalScope.launch {
        userManager.storeUser(email,password)
    }
}

private fun observeData() {

    //Updates age
    userManager.userAgeFlow.asLiveData().observe(this, {
        age = it
        dataStoreEmail = it.toString()
    })

    //Updates name
    userManager.userNameFlow.asLiveData().observe(this, {
        name = it
        dataStorePassword= it.toString()

    })

    println("================================== " + dataStoreEmail + "  ====================" + dataStorePassword)

}

And when i try to access any of theese methods i get:

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.myapp, PID: *
    kotlin.UninitializedPropertyAccessException: lateinit property userManager has not been initialized

>Solution :

As described in the error message, you have a lateinit property that wasn’t initialized:

lateinit var userManager: UserManager

You need to initialize it before use it as follows:

userManager = UserManager(this) // From MainActivity
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading