Use a variable in an activity declared in another activity

0

In my application I have a SharedPreference variable that stores an int value for me. This value has to decrease as the user performs some actions, as if it were a counter. Let's say that each time the user presses a specific button this value stored in SharedPreference decreases by 1 and has to be stored again with the updated value.

What happens is that I declare this SharedPreference variable in MainActivity which is the main code however, this screen appears only once. After the user enters a value that will be requested for it and this value is entered in the SharedPreference the application will start being executed from another screen. And it is in this other screen that the value undergoes its decrease as the button is clicked. And then I caught. I do not know if I use Intent to pass the parameter, but how can I store the updated value, since this activity will not be more open.

Is there a way to use this variable in both activity? Or something like that.

    
asked by anonymous 20.03.2015 / 19:41

1 answer

2

In MainActivity to write the value in SharedPreference you should be doing something like this;

SharedPreferences cod_final = PreferenceManager.getDefaultSharedPreferences(context);
cod_final.edit().putInt("codfinal", mostrarTexto).apply();  

In the Activity you will need to read the recorded value to use it and save it again:

SharedPreferences cod_final = PreferenceManager.getDefaultSharedPreferences(context);
//Ler o valor guardado de mostrartexto
int mostrarTexto = cod_final.getInt("codfinal", 0);
// use agora mostrarTexto como quizer, por ex. somar mais 1
mostrarTexto = mostraTexto + 1;
//grave novamente o novo valor de mostarTexto
cod_final.edit().putInt("codfinal", mostrarTexto).apply();

Back to MainActivity use this same code to read the changed value.

Simplifying:
To save use:

SharedPreferences cod_final = PreferenceManager.getDefaultSharedPreferences(context);
cod_final.edit().putInt("codfinal", mostrarTexto).apply();

To read use:

SharedPreferences cod_final = PreferenceManager.getDefaultSharedPreferences(context);
int mostrarTexto = cod_final.getInt("codfinal", 0);
    
20.03.2015 / 20:03