I'm trying to add an animation to a textview when my activity start. However, I get this error (10 seconds) after my activity starts. This is the log:
FATAL EXCEPTION: Thread-10028
Process: be.ugent.myapplication, PID: 14929
android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:6462)
at android.view.ViewRootImpl.invalidateChildInParent(ViewRootImpl.java:932)
at android.view.ViewGroup.invalidateChild(ViewGroup.java:4693)
at android.view.View.invalidateInternal(View.java:11806)
at android.view.View.invalidate(View.java:11770)
at android.view.View.startAnimation(View.java:17877)
at be.ugent.myapplication.SplashScreen$1.run(SplashScreen.java:40)
and this is my SplashScreen.Java:
public class SplashScreen extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
final TextView wtext = (TextView)(findViewById(R.id.wtext));
Thread mSplashThread;
Animation animation = AnimationUtils.loadAnimation(this, R.anim.abc_fade_in);
wtext.startAnimation(animation);
// The thread to wait for 5 seconds
mSplashThread = new Thread() {
@Override
public void run(){
try {
Thread.sleep(10000);
}
catch(InterruptedException ex){
} finally{
//start animation for fadeout after 5 seconds
Animation animation1 = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.abc_fade_out);
wtext.startAnimation(animation1);
//Start next activity
Intent intent = new Intent(SplashScreen.this,MainActivity.class);
startActivity(intent);
}
}
};
mSplashThread.start();
}
}
Can someone take a look at it? Thanks! Kind regards!
You have to affect views only from UI thread. As a solution you can use handler created in UI thread.
protected void onCreate(Bundle savedInstanceState) {
Handler handler = new Handler();
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
final TextView wtext = (TextView)(findViewById(R.id.wtext));
Thread mSplashThread;
Animation animation = AnimationUtils.loadAnimation(this, R.anim.abc_fade_in);
wtext.startAnimation(animation);
Runnable task = new Runnable() {
public void run() {
Animation animation1 = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.abc_fade_out);
wtext.startAnimation(animation1);
//Start next activity
Intent intent = new Intent(SplashScreen.this,MainActivity.class);
startActivity(intent);
}
}
handler.postDelayed(task, 10000);
...
}