0

该函数包含在主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;
        }

PreferenceConnector 类简化了 SharedPreferences 的工作。函数 checkScore() 应该在其他类中可用,所以需要做静态。但我有错误:

Cannot use this in a static context

该怎么做以及如何解决?

活动:

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;
    }
}
4

3 回答 3

0

您必须将 ACTIVITY 的 CONTEXT 传递给 PreferenceConnector 类

并且您必须制作 PreferenceConnector 类的对象,那时您可以将 Activity 的 Context 传递给该类。

并且不要让方法writeInteger(this, "maxscore", scoreCurrent); 静止的

通过在 Main Activity 中创建 PreferenceConnector 类的对象来使用它。

于 2012-07-28T11:06:44.640 回答
0

试试下面的代码:

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;
        }

(或者)

public int checkScore(int scoreCurrent) {
             int maxscore = PreferenceConnector.readInteger(getApplicationContext(), "maxscore", 0);
             if (scoreCurrent > maxscore) {
              PreferenceConnector.writeInteger(getApplicationContext(), "maxscore",
                             scoreCurrent);
              maxscore = scoreCurrent;
             }
             return maxscore;
            }
于 2012-07-28T11:14:36.257 回答
0

您可以将 GameScreen 活动的引用传递给您的其他类。那么你不需要任何东西是静态的。你可以打电话myGameScreen.checkScore()

于 2012-07-28T15:17:08.060 回答