Let's say First.class has a variable String currentValue = "Red" with a button that leads to Second.class (an activity). First.class(Activity) displays in a textview what the variable currentValue happens to be. (Currently, Red).
If we push the button, it takes us to Second.class, which has an EditText box to modify the variable in First.class. It also has a button to confirm the change. Finally, it has a TextView at the very bottom showing a preview of what First.class' value variable is.
When a user types in "Blue" in Second.class' EditText box and hits the button, how would we change the variable from First.class without using intents and going back to that activity? I want to stay within Second.activity and do the changes from there.
After hitting the confirm button, the preview TextView should update to match the newly modified variable. We should still be seeing Second.class, I remind you. If the user hits "Back" or "up" at this point, they should return to First.class and also see that the TextView in First.class has been changed.
How do I modify First.class' variables if Second.class is entirely separate from First.class and cannot access it? (First.class is the hierarchical parent of Second.class.
You can't or (more importantly) you should not try to do this.
The Android
Activity
is a "special case" class and should be generally considered as being self-contained. In other words any changes to data in the secondActivity
which need to be reflected in the firstActivity
must be either persisted using some form of global storage (SharedPreferences
for example) or should be passed using the extras of anIntent
or aBundle
.With
SharedPreferences
simply have the firstActivity
save yourcurrentValue
before starting the secondActivity
and do the reverse in secondActivity
before returning to the first. The firstActivity
then simply needs to check theSharedPreferences
inonResume()
and update itsTextView
if necessary.As codeMagic mentioned, however, simply using
startActivityForResult(...)
would allow passingcurrentValue
from the first to the secondActivity
and, before the second exits, updating theBundle
with any changes will allow it to be passed back to the firstActivity
throughonActivityResult(...)
.