Request a value only once, save it and accumulate it to use it always in java with Android studio

0

Good day,  I have in this interface where in the EditTex marked in red is a value that I want to leave fixed after I request it once

From this activity I send it to another activity2 where I have this structure.

 Bundle bundle = getIntent().getExtras();
    if(bundle !=null) {

        uni =bundle.getString("u");
    }

to collect the uni data, in that same activity I have a method where I use that variable

String miunidades=uni;
int valorUnidad = Integer.parseInt(miunidades);

I convert it because it comes in String and then I perform the operation

if(suma == 1){
      valorUnidad=valorUnidad+0;
         }if(suma==2) {
            valorUnidad = valorUnidad + 2;
                }if(suma==3){
                     valorUnidad=valorUnidad+2;
               }
                textViewcalculo.setText("Dosis: "+valorUnidad);

And that value I do not want to re-start the application because I need it to be cumulative and save it and take that again and continue the operation.

Thanks

    
asked by Julian 20.10.2018 в 18:59
source

1 answer

0

To save values and not be lost when the app is closed you must use the SharedPreferences.

Here is an example of how to save a String and an int

SharedPreferences sharedPref = myContext.getSharedPreferences(
            SHARED_FILE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString(KEY_1, myText);
editor.putInt(KEY_2,myNumber);
editor.apply(); //Sin esto no se guarda nada

And here as you do to read the data later

SharedPreferences sharedPref = context.getSharedPreferences(
            SHARED_FILE_NAME, Context.MODE_PRIVATE);
String myText = sharedPref.getString(KEY_1,""); //El segundo parametro es el valor por defecto en caso de que no hayas guardado nada todavia.
int myNumber = sharedPref.getInt(KEY_2,0);

As you will see it is similar to the handling of a Bundle, so you will not have problems.

    
answered by 20.10.2018 в 19:52