what is the Best way to use shared preferences between activities

后端 未结 4 821
悲哀的现实
悲哀的现实 2020-12-08 16:13

I have a user preference in my app, which gets used by different activities. I would like to know the best way to utilize those preferences between different activities in m

4条回答
  •  星月不相逢
    2020-12-08 16:20

    You can use this way and declare same variables with same name in all activites where you want to use.

      public static final String PREFS_NAME = "MyPrefsFile";
      static SharedPreferences settings;
      SharedPreferences.Editor editor;
      int wordCount;
    
     public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    
        settings = getSharedPreferences(PREFS_NAME, 0);
        editor = settings.edit();
    
        wordCount = settings.getInt("wordCount", 4); 
    
      }
    

    Here initially wordCount will give 4; And when you edit wordCount and want to store again

      editor.putInt("wordCount", 6);
      editor.commit();
    

    You have to declare this same variables in activities where you want to use shared preferences. And its better you call getSharedPreferences in every activity.

    I don't think that passing that preference in intent will work.

提交回复
热议问题