Search code examples
androidkotlinsharedpreferencesonactivityresult

What could be causing SharedPreferences do not update?


My app consists of playing simple games and earn some points and then withdraw these points to an external account. I am saving these points in the SharedPreferences to avoid multiple requests to the server (I still validate them when the user wants to withdrawn, but this is not relevant for my problem).

Now, the code goes something like this:

UserActiviy

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()
}

The user transfers his points, and then the finishTransaction function is called setting the result as OK and finishing the activity. The parent activity handles the onActivityResult and if the result was OK, it updates the SharedPreferences and UI.

This works perfectly on all the devices that I tested, but for some reason, some of my users are having a different outcome. When they transfer successfully, the SharedPreferences and UI are not being updated correctly.

I cannot replicate this behavior so I can fix it. So I was hoping if someone that had some similar problems could lead me here. I am thinking that maybe the resultCode is not RESULT_OK and the transactionSuccessfully is not being called because of that, but as I said, I am not being able to replicate this.

Does anyone has had a similar problem that could help me?


Solution

  • This is just speculation but if possible call

    super.onActivityResult(requestCode, resultCode, data)
    

    last. Ideally you want to run it first but I've had issues where it led to unexpected behavior concerning my code inside of my @override.