0

Suppose i have a timer which uses a TextView in Fragment A. And i want to use this timer in Fragment B. How would i do it? This is the code which is being used in Fragment A to set the timer...

private Runnable mUpdateTimeTask = new Runnable() {
    public void run() {
        long totalDuration = mp.getDuration();
        long currentDuration = mp.getCurrentPosition();

        // Displaying total duration time
        songTotalDurationLabel.setText(""+utils.milliSecondsToTimer(totalDuration));
        // Displaying current time
        songCurrentDurationLabel.setText(""+utils.milliSecondsToTimer(currentDuration));

        // Running this thread after 100 milliseconds
        mHandler.postDelayed(this, 100);
    }
}; 

Now i want to use the timer that's associated with the songCurrentDurationLabel TextView, in Fragment B as well.

How would i go about solving this?

Thanks!

Jamie Smith
  • 131
  • 8
  • You shouldn't update your UI from outside of your main thread. – dazito Apr 17 '16 at 17:49
  • Can you please explain? – Jamie Smith Apr 17 '16 at 17:52
  • check the explanation to this question: http://stackoverflow.com/questions/4369537/update-ui-from-thread *but* do not use AsyncTask, you will run into problems later on (like memory leaks when you rotate the device). Read more about it here: http://simonvt.net/2014/04/17/asynctask-is-bad-and-you-should-feel-bad/ – dazito Apr 17 '16 at 18:02

1 Answers1

0

Use timer in the host Activity and set/post results as callbacks. Android UI toolkit is not thread-safe - don’t access the UI from outside the UI thread.

Check some gotchas.

Maxim G
  • 1,479
  • 1
  • 15
  • 23