25

I load from activity A the SharedPreferences in following way:

private void SavePreferences(String key, String value){
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);

    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putString(key, value);
    editor.commit();
}

At activity B I want to load the SharedPreferences. Following was a NullPointerException:

private void LoadPreferences(){   
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    data = sharedPreferences.getString("name", "08:00") ;
}

If I try following, I get this compilation error: "No enclosing instance of the type A is accessible in scope"

private void LoadPreferences(){   
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(A.this);
    data = sharedPreferences.getString("name", "08:00") ;
}

How can I access the data?

Armand
  • 23,463
  • 20
  • 90
  • 119
user1390816
  • 623
  • 2
  • 13
  • 34

1 Answers1

49

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.

ρяσѕρєя K
  • 132,198
  • 53
  • 198
  • 213
  • 1
    I changed "this" to getApplicationContext(), and now it works. Thank you very much! – user1390816 Jul 03 '12 at 18:33
  • ^ Sometime you might need to pass the SharedPreference object when you are calling the a function from Activity A to B. – Shobhit Puri Apr 09 '13 at 06:06
  • 1
    It should not make a difference - your answer is confusing - the OP probably had some other problem and apparently changed something else in the code – Mr_and_Mrs_D Jan 12 '14 at 12:37