How to implement SharedReferences in Android Studio?

0

Good day, I have a code model using intent in the following way and I want to pass it, I do not know how to use SharedReferences

        unidades=(EditText)findViewById(R.id.editTextunidades);
        Intent miinten = new Intent(Calculate.this, Hitorial.class);
        u= unidades.getText().toString();

        miinten.putExtra("u", u);
        startActivity(miinten);

And in activity 2 in my case Hitorial I have

private String uni;

 Bundle bundle = getIntent().getExtras();
    if(bundle !=null) {
        uni =bundle.getString("u");
    }

What I want is to be able to use references for that value that is saved in uni, I want to save it once and have it in the app already saved and be able to operate it and have it accumulated

    
asked by Julian 20.10.2018 в 20:41
source

1 answer

0

Add the methods to save and get the preference value:

private String PREFS_KEY = "mispreferencias";

public void guardaValor(Context context, String text) {
    SharedPreferences settings = context.getSharedPreferences(PREFS_KEY, MODE_PRIVATE);
    SharedPreferences.Editor editor;
    editor = settings.edit();
    editor.putString("valorU", text);
    editor.commit();
}



public String obtieneValor(Context context) {
    SharedPreferences preferences = context.getSharedPreferences(PREFS_KEY, MODE_PRIVATE);
    return  preferences.getString("valorU", "");
}

Later in Activity 2 you must validate if this value has been saved, if this is the case, it is obtained from preferences otherwise it is obtained from the bundle and saved in preferences:

String valorU = obtieneValor(getApplicationContext());
if(valorU == null || valorU.length() == 0){
//No existe valor guardado en preferencias.
//Obtiene valor de intent y guarda en preferencias.
  Bundle bundle = getIntent().getExtras();
      if(bundle !=null) {
          uni =bundle.getString("u");
          guardaValor(getApplicationContext(), uni);
      }
}else{
//asigna valor que fue guardado previamente en preferencias.
 uni = valorU;
}
    
answered by 20.10.2018 в 21:53