How to maintain the state of an activity at the time of clicking back button and coming back to the same activity

StackOverflow https://stackoverflow.com/questions/7081060

  •  15-12-2020
  •  | 
  •  

質問

I have a question related to navigation between different activities and onPause and onRestore might solve the problem but how that I don't know.

The problem is I have following screens in my application

  1. HomeActivity - This is the welcome screen
  2. CategoryActivity - Here there are three categories e.g. Animal, Plants and Fruits.
  3. QuestionsActivity - Here each questions are available according to selection of Category. In each cateogry there are 50 questions.The application has multiple choice type of questions.

so the flow of application is when a user comes and selects a category, I populate an arraylist of 50 questions from my xml for that category, then display those questions one by one on the QuestionActivity screen. Here, every time a user clicks on the category, I shuffle the arraylist and show the count. i.e you finished 1 question, you finished 2 question etcs.

So this is something about my application and now problem:

Suppose a user is in QuestionActivty and he answered 5 questions and then click on back button of mobile so he is redirected to the CategoryActivity screen. Now from here, if he again clicks on the same Category, he is redirected to the QuestionActivity screen but his questions starts from 1st questions :(. Ideally, it should start with 6th question as he already aswered 5 questions.

Can some one please help me to solve this problem? If I persist the count, then it won't work for me as every time I am shuffling the arraylist (so the answered questions might repeat.) What the ideal solution should be is to let android manage the state of QuestionActivity at the time of click of back button and resume the same state at the time of again selecting the same Category

This must be a common problem so if you already solved it, please help me out.

Thanks a lot in advance, Ishan

役に立ちましたか?

解決

Why not use StartActivityForResult(). Send back an int x = 5 back to CategoryActivity and then when you resume QuestionActivity you can send x back with it in the Bundle extras. SO then QuestionActivity knows to start form the 6th (x+1) question.

If the questions are randomly ordered you will have problems, since the 6th question might be the same as the first five. So instead of sending just an int x back, send an Integer Array of the question numbers that have already been answered.

他のヒント

I'd suggest looking into storing this data in either a SQLite DB or in a SharedPreferences file. This way you can record where your user has left off and present the next questions based on values within one of these storage mechanisms.

http://developer.android.com/guide/topics/data/data-storage.html

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top