我正在开发一个测试应用程序,我正在尝试在应用程序中添加一个积分系统,这样,每当用户正确回答问题时,都会得到一个+1分。为了存储我使用的jetpack的要点,编写preferences、Datastore、。问题是,每当我想在已经保存的点中添加一个点时,它就不工作了。
,这是我的PointsData
class PointsData(private val context: Context) {
//create the preference datastore
companion object{
private val Context.datastore : DataStore<Preferences> by preferencesDataStore("points")
val CURRENT_POINTS_KEY = intPreferencesKey("points")
}
//get the current points
val getpoints: Flow<Int> =context.datastore.data.map { preferences->
preferences[CURRENT_POINTS_KEY] ?: 0
}
// to save current points
suspend fun SaveCurrentPoints(numPoints : Int){
context.datastore.edit {preferences ->
preferences[PointsData.CURRENT_POINTS_KEY] = numPoints
}
}
}保存点方法
class SavePoints {
companion object {
@Composable
fun savepoints(numPointsToSave : Int) {
val context = LocalContext.current
val scope = rememberCoroutineScope()
val datastore = PointsData(context)
LaunchedEffect(1) {
scope.launch {
datastore.SaveCurrentPoints(numPointsToSave)
}
}
}
}
}每当我想从我的DataStore中得到点数时,我使用
val pointsdatastore = PointsData(context)
val currentpoints = pointsdatastore.getpoints.collectAsState(initial = 0)
//display it as text for example
Text(text = currentpoints.value.toString(), fontSize = 30.sp, fontWeight = FontWeight.Bold,
color = Color.White)来完成我想要的操作(添加+1o),我做了下面的工作
val pointsdatastore = PointsData(context)
val currentpoints = pointsdatastore.getpoints.collectAsState(initial = 0)
SavePoints.savepoints(numPointsToSave = currentpoints.value + 1)但是它似乎不起作用,因为点数总是保持在1。
,如果你知道什么问题,请帮助。
发布于 2022-09-14 20:59:35
我自己找到了答案,但是对于任何陷入同样情况的人来说,解决方案是PointsData中的另一种方法(请看提供的代码)
方法是:
suspend fun incrementpoints(){
context.datastore.edit { preferences->
val currentpoints = preferences[CURRENT_POINTS_KEY] ?: 0
preferences[CURRENT_POINTS_KEY] = currentpoints + 1
}
}(如果您想要减少而不是增量,则只需将+改为- )
现在在PointsMethod(查看提供的代码的问题)中,您应该添加
@Composable
fun incrementpoints() {
val context = LocalContext.current
val scope = rememberCoroutineScope()
val datastore = PointsData(context)
LaunchedEffect(key1 = 1) {
scope.launch {
datastore.incrementpoints()
}
}
}https://stackoverflow.com/questions/73682304
复制相似问题