title: Android Fragments and Separate Threads
body: <p>I am using the android ViewPager : <a href="http://developer.android.com/reference/android/support/v4/view/ViewPager.html" rel="noreferrer">http://developer.android.com/reference/android/support/v4/view/ViewPager.html</a></p>
  
  <p>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.</p>
  
  <p>I extended a thread which would call <a href="http://developer.android.com/reference/android/support/v4/view/ViewPager.html#setCurrentItem%28int,%20boolean%29" rel="noreferrer" title="setCurrentItem">setCurrentItem</a> on my ViewPager which I passed in through an argument. When I did that I received this:</p>
  
  <pre><code>java.lang.IllegalStateException: Must be called from main thread of process
  </code></pre>
  
  <p>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:</p>
  
  <pre><code> 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)
  </code></pre>
  
  <p>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. </p>
  
  <p>So my question is:</p>
  
  <p>Is it possible to inject something along the lines of</p>
  
  <pre><code>run() { while(condition) { methodIWantHere(); sleep(timeout); } }
  </code></pre>
  
  <p>inside my main activity's thread without disrupting it?</p>
  
  <p>OR</p>
  
  <p>What is a better design pattern to achieve the effect I would like? (which is to change the view at consistent specified intervals)</p>