[英]How to save a state of a variable in android app and use it
我有一个基于eclipse构建的android应用。 我目前正在做的事情是随机询问xml文件中的一组问题。 Xml文件如下所示:
<item>
<ques></ques>
<option1></option1>
<option2></option2>
<option3></option3>
<ans></ans>
<level>1</level>
</item>
<item>
<ques></ques>
<option1></option1>
<option2></option2>
<option3></option3>
<ans></ans>
<level>1</level>
</item>
<item>
<ques></ques>
<option1></option1>
<option2></option2>
<option3></option3>
<ans></ans>
<level>2</level>
</item>
等等...
现在,我正在从第一级中随机选择问题。 像第1级有50个问题,第2级有50个问题。我现在想按顺序选择问题。 就像从上到下开始。 就像用户A登录游戏时一样,他从级别1被问到问题a和b。然后他关闭游戏并再次登录,因此他现在应该看到c和d。
我的问题是如何在Android中保存此状态? 有没有简单的方法可以做到这一点?
您可以做的是为每个级别编号
对于1级问题,一个int变量可以跟踪用户所在的问题。 你可以有
int questionNumber;
在您的方法中声明用户遇到的每个问题
questionNumber++;
现在,当玩家退出活动或退出应用程序时。
像这样将问题编号放在“ 共享首选项”中 。
SharedPreferences app_preferences =
PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = app_preferences.edit();
editor.putInt("questionNumber", questionNumber);
editor.commit(); // Very important
现在把号码拉出来就好了。
SharedPreferences app_preferences =
PreferenceManager.getDefaultSharedPreferences(this);
// Get the value for the run counter
questionNumber = app_preferences.getInt("questionNumber", 0);// The 0 is there for if the user hastn played before it is set to 0 automatically or you can set it to 1
编辑:
您也可以使用一个变量来跟踪用户所在的级别,例如
int userLevel;
只需像以前一样将其保存到共享首选项即可。
使用SharedPreferences来存储和检索值...非常易于使用。( http://developer.android.com/reference/android/content/SharedPreferences.html )。
最简单的方法是使用共享首选项。 有关相关文档的指针,请参阅指南主题数据存储 。
将其存储在Android设备上: http : //developer.android.com/guide/topics/data/data-storage.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.