Android Fragments and Separate Threads

android, android-fragments, multithreading

Solution

A `Handler` would be an obvious choice.

final Runnable changeView = new Runnable()
{
    public void run() 
    {
        methodIWantHere();
        handler.postDelayed(this, timeout);
    }
};

handler.postDelayed(changeView, timeout);

Problem

I am using the android ViewPager : http://developer.android.com/reference/android/support/v4/view/ViewPager.html This class allows you to basically slap a bunch of Views or Fragments into a group and page through them easily. My problem occurs when I try to create a separate thread to randomly shuffle through the views. I extended a thread which would call setCurrentItem on my ViewPager which I passed in through an argument. When I did that I received this: ``` java.lang.IllegalStateException: Must be called from main thread of process ``` I figured all I would have to do to fix that would be to call a method from my activityfragment so I created changePageFromActivity to do the dirty work and called that by passing my activity to my thread. But that didn't work either. Below is the full stack trace: ``` FATAL EXCEPTION: Thread-11 java.lang.IllegalStateException: Must be called from main thread of process at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1392) at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:431) at android.support.v4.app.FragmentStatePagerAdapter.finishUpdate(FragmentStatePagerAdapter.java:160) at android.support.v4.view.ViewPager.populate(ViewPager.java:804) at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:433) at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:405) at android.support.v4.view.ViewPager.setCurrentItem(ViewPager.java:397) at com.lyansoft.music_visualizer.MusicVisualizerActivity.changePageFromActivity(MusicVisualizerActivity.java:144) at com.lyansoft.music_visualizer.ShuffleThread.run(ShuffleThread.java:38) ``` After doing some research I gathered that Fragments are easily destroyed and result in a different thread so to prevent any problems ViewPager just made sure that the method I wanted had to be called from the main activity. So my question is: Is it possible to inject something along the lines of ``` run() { while(condition) { methodIWantHere(); sleep(timeout); } } ``` inside my main activity's thread without disrupting it? OR What is a better design pattern to achieve the effect I would like? (which is to change the view at consistent specified intervals)

Original source