简体   繁体   中英

Java & Android & SharedPreferences & OOP

The function contains in the main Activity:

public int checkScore(int scoreCurrent) {
         int maxscore = PreferenceConnector.readInteger(this, "maxscore", 0);
         if (scoreCurrent > maxscore) {
          PreferenceConnector.writeInteger(this, "maxscore",
                         scoreCurrent);
          maxscore = scoreCurrent;
         }
         return maxscore;
        }

The class PreferenceConnector simplifies work with SharedPreferences. Function checkScore() should be available in other classes, so need to do static. But i have error:

Cannot use this in a static context

What to do and how to fix?

Activity:

public class GameScreen extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

    }

    public static int checkScore(int scoreCurrent) {
        int maxscore = PreferenceConnector.readInteger(GameScreen.this,
                "maxscore", 0);
        if (scoreCurrent > maxscore) {
            PreferenceConnector.writeInteger(GameScreen.this,
                    "maxscore", scoreCurrent);
            maxscore = scoreCurrent;
        }
        return maxscore;
    }
}

You have to pass CONTEXT of your ACTIVITY to the class PreferenceConnector

And you have to make the object of the class PreferenceConnector, at that time you can pass your Activity's Context to that class.

And don't make the method writeInteger(this, "maxscore", scoreCurrent); STATIC

Use it by creating the object of PreferenceConnector class in your Main Activity.

Try this below code:

public int checkScore(int scoreCurrent) {
         int maxscore = PreferenceConnector.readInteger(YourActivityName.this, "maxscore", 0);
         if (scoreCurrent > maxscore) {
          PreferenceConnector.writeInteger(YourActivityName.this, "maxscore",
                         scoreCurrent);
          maxscore = scoreCurrent;
         }
         return maxscore;
        }

(or)

public int checkScore(int scoreCurrent) {
             int maxscore = PreferenceConnector.readInteger(getApplicationContext(), "maxscore", 0);
             if (scoreCurrent > maxscore) {
              PreferenceConnector.writeInteger(getApplicationContext(), "maxscore",
                             scoreCurrent);
              maxscore = scoreCurrent;
             }
             return maxscore;
            }

You could just pass a reference to the GameScreen activity to your other classes. Then you don't need anything to be static. You could just call myGameScreen.checkScore() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM