1

What is THE BEST way for this?

Is it only possible to do it through static variables?

Case: Given two activities (Main and Main2), if I want to keep the changes I make on Main2 (using Intent), do I need to save the changes in Main (with static vars) so I can retrieve them later in Main2 again?

JDJ
  • 4,298
  • 3
  • 25
  • 44
  • Could you describe a more concrete example of what kind of information you want the other activity to access? – JDJ Jun 28 '14 at 03:31
  • Yes, for instance, a "Settings" activity where I store the user preferences. I want to know which parametres were checked by the user so I do something in "Main Activity". – user3785125 Jun 28 '14 at 03:34
  • Okay, see my answer below. – JDJ Jun 28 '14 at 03:39

1 Answers1

0

Generally you shouldn't rely on storing persistent data in an Activity. Each Activity constantly cycles through lifecycle changes that are often out of your control. So you probably shouldn't store static variables in your activities that you want other activities to access.

You can use the SharedPreferences API to store user preferences.

If you need to store application-wide values that each of your activities can access, you could consider storing them in a class that extends the Application class, or create a static singleton to store them in.

EDIT: Here is a discussion involving the use of the Application class versus using a static singleton to store global application state.

Community
  • 1
  • 1
JDJ
  • 4,298
  • 3
  • 25
  • 44
  • 1
    Making your own Application is no longer considered a good idea- its confusing and adds no value. Doing it as a standard Java singleton or in a class that holds globals is preferred. – Gabe Sechan Jun 28 '14 at 03:43
  • Good point. I'll add a link so they can read about that debate. – JDJ Jun 28 '14 at 03:46
  • This is first hit when I searched "how to access variables from application in activities on android" so if you could describe how we go about interacting with variables from an the application in an activity that would be awesome. – kpie Mar 29 '18 at 17:52