如何保存变量的状态Android应用程序,并使用它 [英] How to save a state of a variable in android app and use it

查看:179
本文介绍了如何保存变量的状态Android应用程序,并使用它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我这是基于Eclipse构建Android应用程序。什么我目前做的是要通过一系列的xml文件的问题随机问。 xml文件看起来是这样的:

I have an android app which was built on eclipse. What i am currently doing is going through set of question in xml file randomly to ask. Xml file looks like this:

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

等等....

从任意一个级别现在我选择的问题。像有在2级1级和50 50的问题,我想现在选择顺序问题。像从从上到下开始。就像如果剧本用户A登录他被问的问题a和b的比赛从1级然后他关闭游戏,并再次重新登录,所以他应该看到C和D了。

Right now i am selecting question from level one randomly. Like there are 50 question in level 1 and 50 in level 2. I want to select question in order now. Like start from the top to bottom. Like if user A logs in plays the game he is being asked question a and b from level 1. Then he closes the game and logs back again so he should see c and d now.

我的问题是如何这种状态被保存在android系统?有没有一种简单的方法来做到这一点?

My problem is how can this state be saved in android? Is there a easy way to do this?

推荐答案

你可以做的是,对每个级别有它的编号

What you could do is, is for each level have it numbered

有关1级的问题一个int变量来跟踪问题的用户是对的。你可以有

For level 1 question a int variable to keep track of the question the user is on. You could have

int questionNumber;

在方法声明为用户获取对每个问题

in your method declare for each question the user gets to

 questionNumber++;

现在当玩家离开活动或注销的应用程式。

Now when the player leaves the activity or logs out of the app.

提出的问题数量在共享preference 的这样..

Put the question number in the Shared Preference like this..

  SharedPreferences app_preferences = 
        PreferenceManager.getDefaultSharedPreferences(this);

 SharedPreferences.Editor editor = app_preferences.edit();
    editor.putInt("questionNumber", questionNumber);
    editor.commit(); // Very important

现在拉出来数只使用..

Now to pull the number out just use..

  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

编辑:

你也可以有跟踪水平的用户是在诸如

Also you could have a Variable that keeps track of the Level the user is on such as

int userLevel;

和只是将其保存到共享preference像之前。

And just save it to shared preference as you did before.

这篇关于如何保存变量的状态Android应用程序,并使用它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆