Reputation: 65
I have a small problem, which is probably not the hardest to solve, I just couldn't find anything so far:
In my application I use a progress bar that is connected to a CountDownTimer
. When I flip the device, the Progress Bar resets to 0 and the Timer doesn't which leads to the time being up while the bar is still somewhere in the middle. I use two different layout files for portrait/landscape, but the Progress Bar definition doesn't differ.
This is the java code:
mCountDownTimer=new CountDownTimer(6000,50) {
@Override
public void onTick(long millisUntilFinished) {
Log.v("Log_tag", "Tick of Progress"+ i + millisUntilFinished);
i++;
mProgressBar.setProgress(i);
}
@Override
public void onFinish() {
i++;
mProgressBar.setProgress(i);
Toast toast = Toast.makeText(getApplicationContext(), "Time Up!", Toast.LENGTH_SHORT);
toast.show();
if(counter < DBAdapter.NUMBER_OF_QUESTIONS){
i=0;
newQuestion();
}
else endGame();
}
};
This the xml code:
<ProgressBar
android:id="@+id/progressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:max="120"
android:progress="0"
android:visibility="visible" />
Thank you for your help!
Upvotes: 0
Views: 79
Reputation: 1744
Please note that when a flip occurs you activity gets destroyed and gets re-created again. Hence the values in the local variables get lost.
To avaoid losing such values use onSaveInstanceState()
and onRestoreInstanceState()
to store the progress value and retrieve it back.
Example,
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("PROGRESS VALUE", i);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
i = savedInstanceState.getInt("PROGRESS VALUE");
}
Yo can read more about this here,
http://developer.android.com/training/basics/activity-lifecycle/recreating.html
You can learn more on this here.
http://www.youtube.com/watch?v=2VYlTgaAHTs&list=PLlxmoA0rQ-LyCGSSD_nuPAmXDSR_FU0RR&index=31
http://www.youtube.com/watch?v=7XqHvJK9xn4&list=PLlxmoA0rQ-LyCGSSD_nuPAmXDSR_FU0RR&index=32
http://www.youtube.com/watch?v=4LYhbQXu19U&list=PLlxmoA0rQ-LyCGSSD_nuPAmXDSR_FU0RR&index=33
http://www.youtube.com/watch?v=W3NsvUX_Fwo&list=PLlxmoA0rQ-LyCGSSD_nuPAmXDSR_FU0RR&index=34
I hope this helped you!
Upvotes: 1