i am try to change relative layout background color like blink first set green and after set white background color in relative layout.but, my problem thread execute second time force close error occurs and try to fix lot of way but doesn’t work.
here’s my code:
isThreadRunning = true;
relative=(RelativeLayout) findViewById(R.id.layout);
Runnable runnable = new Runnable() {
public void run() {
int i=0;
while(isThreadRunning) {
if(i==0)
{
relative.setBackgroundColor(Color.GREEN);
i=1;
}
else
{
relative.setBackgroundColor(Color.BLACK);
i=0;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
new Thread(runnable).start();
and i am getting error in logcat like below:
07-10 17:48:42.752: W/dalvikvm(2060): threadid=9: thread exiting with uncaught exception (group=0x40015560)
07-10 17:48:42.756: E/AndroidRuntime(2060): FATAL EXCEPTION: Thread-10
07-10 17:48:42.756: E/AndroidRuntime(2060): android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
07-10 17:48:42.756: E/AndroidRuntime(2060): at android.view.ViewRoot.checkThread(ViewRoot.java:2932)
07-10 17:48:42.756: E/AndroidRuntime(2060): at android.view.ViewRoot.invalidateChild(ViewRoot.java:642)
07-10 17:48:42.756: E/AndroidRuntime(2060): at android.view.ViewRoot.invalidateChildInParent(ViewRoot.java:668)
07-10 17:48:42.756: E/AndroidRuntime(2060): at android.view.ViewGroup.invalidateChild(ViewGroup.java:2511)
07-10 17:48:42.756: E/AndroidRuntime(2060): at android.view.View.invalidate(View.java:5279)
07-10 17:48:42.756: E/AndroidRuntime(2060): at android.view.View.setBackgroundDrawable(View.java:7626)
07-10 17:48:42.756: E/AndroidRuntime(2060): at android.view.View.setBackgroundColor(View.java:7516)
07-10 17:48:42.756: E/AndroidRuntime(2060): at com.example.screen_blinker.Home_activity$1.run(Home_activity.java:44)
07-10 17:48:42.756: E/AndroidRuntime(2060): at java.lang.Thread.run(Thread.java:1019)
What’ wrong in my code and how to fix this issue?
Thanks in Advance!
change your code as use runOnUiThread for Updating UI elements from NON UI Thread: