Reputation: 1112
I'm very new to Andriod development. I'm trying to use Timer (from java.util) to remove a view 1sec after onCreate
, this is what I've wrote.
Timer timer;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
ImageView startup = (ImageView) findViewById(R.id.startup);
startup.setVisibility(View.GONE);
}
}, 1000);
}
Not exactly sure why but my app crashes every time.
It appears that there is something wrong with the timer. I've tried removing the timer and having startup.setVisibility(View.GONE);
in OnCreatee
and it works fine.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView startup = (ImageView) findViewById(R.id.startup);
startup.setVisibility(View.GONE);
//Didn't crash at all!!!
}
It would be great if someone can explain to me why my app crashes when timer
is used.
Upvotes: 0
Views: 131
Reputation: 1006869
Not exactly sure why but my app crashes everytime unless I remove the timer and remove the view instantly.
Use LogCat to examine the Java stack trace associated with your crash.
You will see that your exception is because you are attempting to modify the UI from a background thread. Your run()
method runs on a background thread supplied by Timer
and TimerTask
.
I recommend using postDelayed()
(a method on View
, such as your ImageView
) instead of Timer
, as this avoids the overhead of the background thread and solves your problem.
Upvotes: 3