Jetpack 数据存储实现

Jetpack DataStore implementation

你好,我正在尝试通过观看一些教程将 JetPack 数据存储实现到我的应用程序中,我是 koltin 的新手。 我关注了这个视频中的所有内容: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)

}

当我尝试访问任何这些方法时,我得到:

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

如错误消息中所述,您有一个未初始化的 lateinit 属性:

lateinit var userManager: UserManager

使用前需要初始化如下:

userManager = UserManager(this) // From MainActivity