Home > Enterprise >  Back from Activity2 to Activity1 without loosing score
Back from Activity2 to Activity1 without loosing score

Time:12-26

I have 2 activity's
MainActivity.java & Winner.java i show score in MainActivity and also there is a button called see winner which takes you to second Activity but when I press back button to MainActivity my score's are reset to 0 enter image description here

I pressed 3 points for team A, Now when I come back from seconActivity the score is displayed 0

Second activity [ I didn't added anything but here is the problem] enter image description here When I pressed the back button. I came back to my MainActivity but score is 0 enter image description here

But the score is still 3 as I made score as static, so when I press again 3 button the score becomes 6, but why here it is showing 0

CodePudding user response:

This happens because when you navigate from one activity to another onCreate method called and you lost the last variables you saved in that page.

You can do these things:

  1. Store scores in a class with static variables
  2. Store scores by using shared preferences
  3. Use view models

CodePudding user response:

This happens because you have to use ViewModel to store and manage UI related data

  • Related