Search code examples
androidandroid-intentandroid-bundlestartactivityforresultandroid-savedstate

Getting data from one activity and storing in another activity at app relaunch


I have a game activity that the user gets points by clicking a button. What I want to do is pass those points to the main activity, the first activity the user sees. So for example, the user goes to the game activity, gets some points and quits the application completely. When they relaunch the application they can see the total amount of points they have on the main activity.

I am using startActivityForResults to get the data from the game activity while in the main activity but I am missing something. I think I need to save the points in the Game activity so that when the app is relaunched it gets the stored points. Am I heading down the right direction? And if so how can I save the points?

Another idea I had was while in the Game Activity, when the user gets points, the points get send right away to the main activity and saved there. When the user relaunches the application the main activity does not need to go to Game Activity to find the points, they will be already stored in main activity. Is this way same, better, or worse?


Solution

  • I think what you want to use is SharedPreferences. They are accesible from all activities and persist data across app relaunches. In your MainActivity, you can check in onResume() if there is new data / a new score that the user achieved (and you saved) in the GameActivity.

    Here's a guide on how to use SharedPreferences. Btw. don't get fooled by the name, you can save all kinds of things with them, not only 'preferences'.