Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何保持变量的值直到我重置它?_Java_Android - Fatal编程技术网

Java 如何保持变量的值直到我重置它?

Java 如何保持变量的值直到我重置它?,java,android,Java,Android,我的游戏中有4个益智游戏,比如说子游戏。对于每个用户,都会获得一些积分。在game1结束后,我将赢得的积分设置为一个公共静态int pointsGame1变量。其他游戏也是如此。我在我的主菜单上有一个显示总分的框。我是这样做的: boxTotalPoints.setText("" + pointsGame1 + pointsGame2 + pointsGame3 + pointsGame4); Menu.totalPoints =+ pointsGame1; 问题是当我开始那个活动时,我得到

我的游戏中有4个益智游戏,比如说子游戏。对于每个用户,都会获得一些积分。在game1结束后,我将赢得的积分设置为一个公共静态int pointsGame1变量。其他游戏也是如此。我在我的主菜单上有一个显示总分的框。我是这样做的:

boxTotalPoints.setText("" + pointsGame1 + pointsGame2 + pointsGame3 + pointsGame4);
Menu.totalPoints =+ pointsGame1;
问题是当我开始那个活动时,我得到0000,因为所有变量的起始值都是0

我遇到的第二个问题是,当我完成游戏1时,我将这些点添加到我的totalPoints变量中,也是公共静态int,如下所示:

boxTotalPoints.setText("" + pointsGame1 + pointsGame2 + pointsGame3 + pointsGame4);
Menu.totalPoints =+ pointsGame1;
但当我玩第二场比赛时,它应该合计我所有的积分并显示在mu合计框中,但我只从上一场比赛中获得积分。另外,如果我在第一场比赛中获得60分,它将显示00060


如何解决这两件事?

在活动中使用
SharedReferences

确切地说:使用来自不同活动/服务/意图的共享首选项/。。。您应该将其与mode_MULTI_进程(常量值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);

将所有pointsGame1、pointsGame2、pointsGame3、pointsGame4定义为静态变量,并确保在重置事件中将其重置为默认值(按钮单击事件时可能会重置)。它们是静态变量。我是否在onCreate方法中使用此方法?你可以编辑你的帖子来使用我的变量,只是为了看一些东西。谢谢。@marjanbaz无论你在哪里需要它,在你的应用程序的任何活动中以任何方式。在onCreate()中也可以(但我认为您的代码结构应该更复杂,而不仅仅是onCreate())@marjanbaz如果这些答案中的任何一个帮助了您,您可以通过接受答案(单击左侧的绿色勾号)和/或向上投票(单击左侧的橙色向上箭头)来回报您的声誉。祝你工作顺利!maurizioI编辑了我的评论,也许你没看到。你能用我的变量名编辑你的帖子吗?看看它们去哪里了?@marjanbaz你去哪了!:-)