Trouble saving high score in android app -


i searched online , people 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 want use first line in class other class extends acitivity (it seems this.getsharedpreferences method won't work otherwise). how can this?

you'll have pass context method or class want use getsharedpreferences() in 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 need to, can use getapplicationcontext() provide context accessible anywhere in application.

for more informations check out question 'what context in android?'.


Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -