Android: string value does not fall into general preferences

I created a general privilege for a boolean and a string value. Boolean gets another action. But for the string, I get only the default value.

Homeclass

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    SharedPreferences.Editor spe = prefs.edit();

    spe.putBoolean("flag", true); 
    spe.putString("user", "hello");
    spe.commit(); 

welcome.class

      SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    boolean flag= prefs.getBoolean("flag", false); 
    String user=prefs.getString("user","Nothing");  

      TextView tv = new TextView(this);
      tv.setText("Flag : "+flag+(" User : "+user);

For "user", only "Nothing" is displayed. Where should I fix my code?

+3
source share
1 answer

Try using:

SharedPreferences settings = getSharedPreferences(appName,0);
settings.getBoolean("flag", true);  
settings.getString("user", "hello"); 

And put:

SharedPreferences settings = getSharedPreferences(appName,0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("flag",true);
editor.putString("user","hello");
editor.commit();

This is what I use in my application and it shares booleans / ints / strings that intersect in many classes

Note: appName does not have to be the name of the application, as in the official tutorial.

+8
source

Source: https://habr.com/ru/post/1779996/


All Articles