Bump with this issue this week, and thought would be nice to share. On Android only the main UI thread has access to your view components, you can read about android threads here, this is actually quite common, on Swing we have the same issue.
So I was designing a small view component and I needed a timer to access it from time to time to update the view. But if you try to do this:
Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { myComponent.update } }, 1000, 1000);
You will run into problems, as only the main thread (Activity Thread) can have access to its views. The solution for that is to use Handlers. And there’s a quite simple way of making a handler act as a timer:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | private Handler mHandler = new Handler(); private Runnable updater = new Runnable() { @Override public void run() { Random r = new Random(); int i = r.nextInt(100)+1; EqualizerView view = (EqualizerView)findViewById(R.id.equalizerView1); view.update(i); mHandler.postDelayed(this, 750); } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mHandler.postDelayed(updater, 10); } |
The Handler class has some methods that allows you to execute Runnables and those can have access to the main thread components. To create the illusion of a timer, all you have to do is make your Runnable, after its execution, ask the handler to call itself again.
Just a simple example to help you out!
Happy coding
