Home > Blockchain >  Jetpack DataStore implementation
Jetpack DataStore implementation

Time:11-07

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

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

CodePudding user response:

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
  • Related