I currently have a progress bar that tracks the progress on music files however upon different orientation it doesn't seem to want to update and just stuck at the previous location ?
private ProgressBar musicProgress;
private int updateIncrement;
private int duration;
private int progress;
private int progressUpdate;
Timer timer = new Timer();
TimerTask timerTask;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_current_music);
if (savedInstanceState != null)
{
progressUpdate = savedInstanceState.getInt("PROGRESS");
duration = savedInstanceState.getInt("Duration");
updateIncrement = savedInstanceState.getInt("Update");
musicProgress = findViewById(R.id.p_musicProgress);
musicProgress.setMax(duration);
timer.scheduleAtFixedRate(timerTask = new TimerTask(){
@Override
public void run() {
musicProgress.setProgress(progressUpdate);
}
}, 0, updateIncrement);
}
}
@Override
public void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
outState.putInt("PROGRESS", progressUpdate);
outState.putInt("Update", updateIncrement);
outState.putInt("Duration", duration);
}
public void onPlayClick (View v)
{
Log.d("MP3 Player", "Music Play button pressed");
if(player.getState() == MP3Player.MP3PlayerState.PAUSED)
{
player.play();
}
else if(player.getState() == MP3Player.MP3PlayerState.PLAYING)
{
player.pause();
}
else
{
player.load(musicURL, playbackspeed);
updateIncrement = player.getDuration()/100;
duration = player.getDuration();
musicProgress = findViewById(R.id.p_musicProgress);
musicProgress.setMax(duration);
timer.scheduleAtFixedRate(timerTask = new TimerTask(){
@Override
public void run() {
progress = player.getProgress();
progressUpdate = progress;
musicProgress.setProgress(progressUpdate);
}
}, 0, updateIncrement);
}
}
The issue might be where I set progress = player.getProgress() inside the timer so even after the activity gets destroyed and made again, it'll try to pass the old values inside and continue but then the value gets changed right before the setProgress?
am just really confused at this point
EDIT 1:
Also I know the redundent assignement of player.getProgress() I was hoping that using different variables would allow it to change but couldn't get it to work
Your
progress
is only updated in the timer started inonPlayClick()
and this only updates variables within the activity that don't persist when the activity is re-created. As a quick fix, you can check if the state is playing and start a new timer in theonCreate
method. However, the preferred way to do this would be to decouple your state from your activity entirely and use a ViewModel to keep and persist the data throughout the view's lifecycle.