Reputation: 85
I'm developing a quiz android application, which uses the activity called "question" that displays the questions and the answers.In this activity there is a next button which will increment a variable, the question id, and will restart the same activity.After restarting, the activity will get the variable and displays the next question.My problem is that i need to display a timer on this activity but i need it to continue the countdown even after restarting the activity. I was thinking to create an enum class that will send me the value of the countdown or even a global timer. Any suggestions??
Upvotes: 0
Views: 506
Reputation: 2630
One way to do this would be to store the countdown in a SharedPreferences
object, however this has the disadvantage of not being very modular, as all parts of your program can access the SharedPreferences
object so you have no guarantee that no other classes aren't somehow messing with the countdown timer value.
A more modular approach is to store the countdown value in the intent that you use to launch your new activity. For example:
// To save the data when you start the new activity
Intent newQuestionIntent = new Intent(getApplicationContext(), MyQuizQuestion.class);
newQuestionIntent.putExtra("question_id", myQuestionId);
newQuestionIntent.putExtra("countdown_value", myCountdownTimerValue);
startActivity(newQuestionIntent);
// To restore the data in your new activity
@Override
protected void onCreate() {
Bundle savedData = getIntent().getExtras();
if (savedData.containsKey("question_id")) {
myQuestionId = savedData.getInt("question_id");
}
if (savedData.containsKey("countdown_value")) {
myCountdownTimerValue = savedData.getInt("countdown_value");
}
}
Upvotes: 0
Reputation: 101
You can probably use the current time on the phone. When you start the timer, store the current time in sharedpreferences. After the activity is restarted you can retrieve this value and compare this against the new current time.
This way you dont have to have an active count down timer. The drawback is that the users can "cheat" by changing the time on the phone!
Upvotes: 1
Reputation: 2976
Don't restart your activity, just update the content in it.
If you're set on restarting it you can do the following: (in order of best-to-worst):
Upvotes: 1