Pass data between Activity Android

Asked

Viewed 226 times

0

I’m new to programming for android, and I just made my first app, but I’m having a problem, which is:

My game has the start menu with the button to start the game and the information about the high score.

Starting the game goes to a second screen where the game starts and on the screen shows the current score and the score to be hit.

On that screen I was able to save the data with SharedPreferences, I mean, on that screen is all ok, but I want to put the information of Highscore from that second screen in the first, how to do?

On the Internet I thought to move from the first screen to Monday, but I did not find from the second screen to the first.

1 answer

1

In your case I would recommend that in the method onResume() from the first screen you searched the data stored in Shared Preferences and displayed them. That way, when you are on the second screen and press the "back" button to return to the first screen, the method onResume() will be called and the Highscore will be updated.

On the first screen you can even leave the Highscore display only because of the method onResume(), without having to show it on onCreate(). The life cycle of Activity will make things work properly, since after the onCreate() the onResume() is automatically called.

  • 1

    This may be the easiest solution but it is not the most optimized one. In view of that each time Activity calls the onResume() something will be searched to update the highscore and there will not necessarily be new data there. The best would be to start the second Activity using the startActivityForResult() and leave the preferences query only on onCreate().

  • You’re right, there’s no reason not to startActivityForResult(). The solution would then be thus: http://answall.com/a/73628/357

  • Now, you can’t escape searching for the Highscore in the first Activity because the idea of the AP is to show it also before the game starts. Then the startActivityForResult() be more optimized is questionable.

  • 1

    He will have to search in the first Activity yes. But only in onCreate(). The difference in performance won’t be huge, but between quick exchanges to another App and back in the game, you don’t pay the price for another search on onResume(). Among other scenarios. So, yes, there is a gain, but it’s not something relatively large.

  • 1

    It is not great either because the amount of information accessed in the preferences is small. If it were for a large amount of data, the difference in quickly switching apps would be much more noticeable, for example.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.