Home > Back-end >  Handle onViewCreated() of the previous fragment when the back button pressed
Handle onViewCreated() of the previous fragment when the back button pressed

Time:11-07

I have the ResultFragment. The onViewCreated() method has some logic regarding saving the result. If a user has earned an achievement, a button appears and he can go to the AchievementFragment. However, when the user presses the back button from there, he goes back to ResultFragment and triggers the saving again and that leads to a result duplicate. How can I handle this behavior? I can check if the result is a duplicate, but this is going to hide a symptom and not solve the problem.

CodePudding user response:

If you want to prevent the application from triggering the saving of the result, which leads to duplications when going back, make use of Boolean.

Below there is a simplified pseudo code of what you could use and adapt to your project:


ResultFragment:

Boolean resultObtained = false // place it somewhere that is not reset when going back

if (resultObtained == true) {
    // do not save result
}
else {
    // save result
}

The Boolean can be reset to false when you go back to the homepage. While is true, the ResultFragment should not duplicate the result if you nest the function inside the if statement using the Boolean.

For the Boolean, you could add it somewhere else and make it static, so it is easily accessible from all the fragments. Additionally, you can keep in the same fragment, but you would need to write more code to ensure that it is not reset to false again when going back. Alternatively, you may place it directly in the AchievementFragment and make it static so it stays true when you go back. However, it is up to you how you want to adapt it in your code.

  • Related