Search code examples
javaandroidandroid-fragmentsrunnable

Runnable not running at all inside fragment


I'm trying to connect a SeekBar to MediaPlayer in a fragment but the runnable isn't running at all. I put a log.i in it to see if it runs but nothing happens at all.

I declare Handler as a global variable:

Handler seekHandler;
SeekBar sBar;

And then in onCreateView:

seekHandler = new Handler();
sBar = (SeekBar) v.findViewById(R.id.seekBar1);

Runnable:

Runnable run = new Runnable() {

    @Override
    public void run() {
        sBar.setMax(mp.getDuration());
        sBar.setProgress(mp.getCurrentPosition());
        Log.i("TAG", "I'm running");
        seekHandler.postDelayed(this, 25);
    }
};

mp variable is a MediaPlayer. The problem is that the Runnable doesn't exexute even once. I am using the exact same code in my similar application in activity and it's working completely fine. Is this because runnables act differently in a Fragment? Also I'm using TabLayout with ViewPager and 2 Fragments, if that affects any of this.


Solution

  • you have to run it at lease once before the handler can submit it again.

    From your class you should call seekHandler.post(run), or run.run(); at least once.