How to share / pass data between activities without being by Intent?

0

I have an Android Studio application where, when I click a button, a number is generated in Activity A and stored in another button in Activity B, which is overwritten whenever I generate a new number in Acitivty A. It will be Is it necessary to use mySQL for this or is there another method?

* I / No / I want to start Activity B whenever I send the number to it. I just want to store it without having to go to the screen, but let it stay there when I want to go.

** Please do not be too technical, as I'm still getting familiar with android studio

    
asked by anonymous 14.03.2018 / 05:48

1 answer

1

There is no (secure) form of an "chat" activity directly with another Activity. As Android is architected, different Activities and Services may be in separate processes.

If you wanted to open the other Activity, firing an Intent would be the correct way. But as you do not want, my suggestion is to write the value generated in Activity A in the app configuration:

SharedPreferences prefs;
prefs = PreferenceManager.
        getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor ed = prefs.edit();
ed.putInt("numero", x);
ed.apply();

In Activity B you can read the configuration value:

SharedPreferences prefs;
prefs = PreferenceManager.
        getDefaultSharedPreferences(getApplicationContext());
int x = prefs.getInt("numero", defaultx);

It is also possible for Actiivty B to sign up for notifications when the setting is changed by Activity A:

prefs.registerOnSharedPreferenceChangeListener(this);

In this case your Activity should implement an interface, and the statement looks like:

public class ActivityB extends Activity
      implements SharedPreferences.OnSharedPreferenceChangeListener

and you should declare the method that will be called when some config changes:

public void onSharedPreferenceChanged(
         SharedPreferences sharedPreferences, String key) {
    if (key.equals("numero")) {
        ... numero mudou, atualizar o botao ....
    }
}
    
14.03.2018 / 08:14