sharedPreferences won't share between activities

后端 未结 5 821
温柔的废话
温柔的废话 2020-12-09 09:06

I\'m trying to use SharedPreferences to save settings. But I can\'t seem to get the data to be shared between any of my activities. The code I\'m using does manage to save s

5条回答
  •  温柔的废话
    2020-12-09 09:28

    You are using getPreferences(MODE). Use getSharedPreferences("PREF_NAME", MODE) instead. This way you will provide a name to particular preference and then you can call it by its name (PREF_NAME here) from whatever the activity you want.

    //------get sharedPreferences
    
    SharedPreferences pref = context.getSharedPreferences("PREF_NAME", Context.MODE_PRIVATE);
    
    //-------get a value from them
    
    pref.getString("NAME", "Android");
    
    //--------modify the value
    
    pref.edit().putString("NAME", "Simone").commit();
    
    //--------reset preferences
    
    pref.edit().clear().commit();
    

提交回复
热议问题