0

I searched online and people are doing this:

SharedPreferences prefs = this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
int oldScore = prefs.getInt("key", 0);  
if(newScore > oldScore ){
   Editor edit = prefs.edit();
   edit.putInt("key", newScore);
   edit.commit();
}

But I want to use the first line in a class other than the class that extends Acitivity (it seems the this.getSharedPreferences method won't work otherwise). How can I do this?

Yu Hao
  • 115,525
  • 42
  • 225
  • 281
Fuad
  • 1,309
  • 1
  • 15
  • 30

1 Answers1

1

You'll have to pass a Context to the method or the class you want to use getSharedPreferences() in like so:

public void updateHighScore(Context context, int newScore) {
  SharedPreferences prefs = context.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
  int oldScore = prefs.getInt("key", 0);  
  if(newScore > oldScore) {
   Editor edit = prefs.edit();
   edit.putInt("key", newScore);
   edit.commit();
  }
}

If you really need to, you can use getApplicationContext() to provide a context accessible anywhere in the application.

For more informations check out this question 'What is context in Android?'.

Community
  • 1
  • 1
Bhullnatik
  • 1,193
  • 17
  • 27