How to save data permanently on a screen (Fragment or Activity) on android even if you leave it?

1

I hope you can support me with this doubt that does not let me move forward with the app I'm doing. How can I store two data on the screen2 from the screen1 permanently, so that when I go to another screen and return I still have the same data. For this I have implemented this code. But he keeps losing them:

   final SharedPreferences prefe=this.getActivity().getSharedPreferences("datos", Context.MODE_PRIVATE);
    String idusu= getArguments()!=null ? getArguments().getString("idusu"):"SIN DATOS";
    String gasto= getArguments()!=null ? getArguments().getString("gasto"):"SIN DATOS";
    SharedPreferences.Editor editor = prefe.edit();//SE crea un objeto de la clase Editor,obtengo la referencia del objeto de la clase SharedPreferences
    editor.putString("idusu", idusu);//Mediante el método putString almacenamos en idideta el valor del String cargado en el EditText
    editor.commit();//metodo commit de la clase editor hace que el dato quede almacenado en forma permanente en el archivo de preferencias para k caundo arranq la aplicación se recupere el último idideta ingresado
    //Toast.makeText(getContext(), nombre, Toast.LENGTH_SHORT).show();

    SharedPreferences.Editor editor2 = prefe.edit();
    editor2.putString("gasto", gasto);
    editor2.commit();
    //Toast.makeText(getContext(), gasto2, Toast.LENGTH_SHORT).show();
    String nombre = prefe.getString("idusu", "valor nombre");
    String gasto2 = prefe.getString("gasto", "valor gasto2");
    
asked by Angelica 18.10.2017 в 23:49
source

1 answer

0

I see that you use as storage method SharedPreferences , saving the values is correct but you still need to add the value of "expense":

final SharedPreferences prefe=this.getActivity().getSharedPreferences("datos", Context.MODE_PRIVATE);
    String idusu= getArguments()!=null ? getArguments().getString("idusu"):"SIN DATOS";
    String gasto= getArguments()!=null ? getArguments().getString("gasto"):"SIN DATOS";
    SharedPreferences.Editor editor = prefe.edit();
    editor.putString("idusu", idusu);
    editor.putString("gasto", gasto);
    editor.commit();

The problem for which you are not recovering the previously stored values, is because you are not defining which preference you want to obtain, the name of the preference you defined as "data" ,

>
SharedPreferences prefe = getSharedpreferences("datos", Context.MODE_PRIVATE);

therefore to obtain the values stored in any part of your application, would be done this way:

SharedPreferences prefe = getSharedpreferences("datos", Context.MODE_PRIVATE);
String nombre = prefe.getString("idusu", "valor nombre");
String gasto2 = prefe.getString("gasto", "valor gasto2");
    
answered by 19.10.2017 / 00:04
source