Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Fragments and Separate Threads

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)

like image 985
ebolyen Avatar asked May 28 '12 06:05

ebolyen


1 Answers

A Handler would be an obvious choice.

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

handler.postDelayed(changeView, timeout);
like image 157
Rajesh Avatar answered Nov 09 '22 12:11

Rajesh