Tuesday, July 14, 2015

Threading in android


For this post, I will use Timer as sample app and example for this explanation.
If you already have experience in creating timer in Java SE, then you already know how to use thread/runnable. If not, please view/use this link as reference :

https://docs.oracle.com/javase/tutorial/essential/concurrency/runthread.html

In android you still can use Thread class provided in Java, but you can't make modify any View in thread. There are certain thing you need to handle before you can use it.



Here the example of threading that call View...




If you use this code and run it, you will get this error :

CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views




So, it said only original Thread can call it view.
What is original thread and How to use original thread.

There have two method you can call to use original Thread :
  1. post()
  2. postDelayed()
Firstly, I will show how to create timer using postDelayed() and recursive.


This technique same like setTimeOut() in JavaScript, keep recursive and the flag is false.

Now, how to make the Thread can modify a View.
To make it possible, modified the View in post() method, like below,



Then, if you run it again...the error will not appear..and the program run normally..
here the source code and sample running :

Source Code : timer.zip

Sample Running :


Start Activity




"START" button clicked





"STOP" button clicked





"Reset" button clicked


If you have problem or something to ask that related to java...
you can email or comment on this post...
I will try to find the solution and share it with you..


you can test it by yourself..
i hope you like this souce code...
and please give some comment....
Created By : Z-man, 2015

No comments:

Post a Comment