SharedPreferences from different activity

后端 未结 2 1717
星月不相逢
星月不相逢 2020-12-23 17:38

I load from activity A the SharedPreferences in following way:

private void SavePreferences(String key, String value){
    SharedPreferences sharedPreference         


        
2条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-23 18:09

    use getApplicationContext() instead of this in both Activities as:

    In activity A the SharedPreferences in following way:

     private void SavePreferences(String key, String value){
            SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putString(key, value);
            editor.commit();
            Intent sd=new Intent(this,Secongtess.class);
            startActivity(sd);
           }
    

    and in Activity B get Value as:

     private void LoadPreferences(){   
           SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
         String  data = sharedPreferences.getString("name", "08:00") ;
         Toast.makeText(this,data, Toast.LENGTH_LONG).show();
       }
    

    because as doc says:

    getDefaultSharedPreferences(Context context) :

    Gets a SharedPreferences instance that points to the default file that is used by the preference framework in the given context.

提交回复
热议问题