在重置之前如何保留变量的值?

时间:2013-04-06 20:50:53

标签: java android

我在游戏中有4个益智游戏,子游戏。为每个用户赚取一些积分。在game1结束后,我将获得的积分设置为public static int pointsGame1变量。等等其他游戏。我的主菜单我有一个应该显示总分的方框。我做这样的事情:

boxTotalPoints.setText("" + pointsGame1 + pointsGame2 + pointsGame3 + pointsGame4);

问题是,当我开始该活动时,我得到0000,导致所有变量的起始值为0。

我遇到的第二个问题是当我完成我的game1时,我将这些点添加到我的totalPoints变量,也就是public static int,就像这样:

Menu.totalPoints =+ pointsGame1;

但是当我玩第二场比赛时,它应该总计我所有的分数并将其显示在mu total box中,但相反我只能获得上次比赛的分数。此外,如果我在第一场比赛中获得60分,它将显示00060。

如何解决这两件事?

1 个答案:

答案 0 :(得分:2)

在您的活动中使用SharedPreferences

准确地说:使用来自不同活动/服务/意图/ ...的共享首选项,您应该使用模式MODE_MULTI_PROCESS(常量值int = 4)。如果没有,文件被锁定,只有一个进程可以立即写入它!

SharedPreferences preferences = getSharedPreferences("myapp",4);
SharedPreferences.Editor editor = preferences.edit();
int points= pointsGame1 + pointsGame2 + pointsGame3 + pointsGame4;
editor.putInteger("points", points);
editor.commit();

SharedPreferences preferences = getSharedPreferences("myapp",4);
points= preferences.getInteger("points", 0);
points= point+pointsGame1;
SharedPreferences.Editor editor = preferences.edit();
editor.putInteger("points", points);
editor.commit();

任何时候你需要在活动中保持点数,使用上面的代码。


然后,当您需要从任何活动/流程中检索积分时:

SharedPreferences preferences = getSharedPreferences("myapp", 4);
points= preferences.getInteger("points", 0);