简体   繁体   中英

How to save a state of a variable in android app and use it

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>

so on....

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.

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

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.

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

EDIT:

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

int userLevel;

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

使用SharedPreferences来存储和检索值...非常易于使用。( http://developer.android.com/reference/android/content/SharedPreferences.html )。

The easiest way is to use shared preferences. See the guide topic Data Storage for pointers to the relevant documentation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM