【问题标题】:What could be causing SharedPreferences do not update?什么可能导致 SharedPreferences 不更新?
【发布时间】:2021-05-24 21:58:29
【问题描述】:

我的应用程序包括玩简单的游戏并赚取一些积分,然后将这些积分提取到外部帐户。我将这些点保存在 SharedPreferences 中以避免对服务器的多个请求(当用户想要撤回时我仍然验证它们,但这与我的问题无关)。

现在,代码是这样的:

用户活动

private fun userClickedToWithdraw() {
    startActivityForResult(Intent(this, WithdrawActivity::class.java), RequestCode.RC_WITHDRAW)
}

private fun transactionSuccessfully() {
    //set the user points to zero in the SharedPreferences
    //and updates the UI accordingly
}

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    if (requestCode == RequestCode.RC_WITHDRAW && resultCode == RESULT_OK) transactionSuccessfully()
}

WithdrawActivity

//handles the transaction and then call finishTransaction

private fun finishTransaction() {
    setResult(RESULT_OK)
    onBackPressed()
}

用户转移他的积分,然后调用finishTransaction函数将结果设置为OK并完成活动。父 Activity 处理 onActivityResult,如果结果正常,它会更新 SharedPreferences 和 UI。

这在我测试的所有设备上都能完美运行,但由于某种原因,我的一些用户得到了不同的结果。当他们成功传输时,SharedPreferences 和 UI 没有正确更新。

我无法复制此行为,因此我可以修复它。所以我希望有类似问题的人能把我带到这里。我在想也许 resultCode 不是 RESULT_OK 并且 transactionSuccessfully 因此没有被调用,但正如我所说,我不是能够复制这个。

有没有人遇到过类似的问题可以帮助我?

【问题讨论】:

    标签: android kotlin sharedpreferences onactivityresult


    【解决方案1】:

    这只是猜测,但如果可能的话,请致电

    super.onActivityResult(requestCode, resultCode, data)
    

    最后。理想情况下,您想先运行它,但我遇到了一些问题,导致我的 @override 中的代码出现意外行为。

    【讨论】:

    • 感谢您的提示。如果可行,我会尝试并更新这篇文章!
    • 我已经根据您的建议进行了更新,看来它确实解决了我的问题。我调查了一下,似乎 super.onActivityResult 没有关于 Activity 类的代码,但它有关于 AppCompactActivity 类的代码,并且由于我的 Activity 是 AppCompactActiviy,我认为他正在做一些忽略我下一个代码的事情。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-26
    • 1970-01-01
    • 2011-02-19
    • 1970-01-01
    相关资源
    最近更新 更多