Eyad Lotfy
Eyad Lotfy

Reputation: 67

Why is the button.setText() shows error

I made a function that is called every 1 second and within that function I wrote

myButton.setText("Stop");

now everything works great without that code,but whenever I write this code,the mobile I make my test on shows message "app has stopped working" I've been looking for a solution 3 days now,help will be appreciated!

this is my code

check_time = new TimerTask() {
@Override
                        public void run() {

                                myButton.setText("Stop");

                            Calendar lo_Calender = Calendar.getInstance();
                            int current_h = lo_Calender.get(Calendar.HOUR);
                            int current_m = lo_Calender.get(Calendar.MINUTE);
                            if (H_toWake == current_h && M_toWake == current_m) {
                                out.println("ring");

                                alarm();

                                //return;
                            } else {
                                out.println("no ring!");
                            }
                        }
                    };
                    time.schedule(check_time, 0, 1000);
}

Upvotes: 0

Views: 150

Answers (2)

Gabe Sechan
Gabe Sechan

Reputation: 93614

First off- the exact bug should be in your logcat. It will tell you what's going wrong. Look there first, on your own.

In this specific case- TimerTasks act on a separate thread. You can only change the UI on the UI thread. Put that part in a runOnUiThread block and you'll be fine.

Upvotes: 1

Helmi
Helmi

Reputation: 556

You cannot touch UI from background thread. use AsyncTask http://developer.android.com/reference/android/os/AsyncTask.html

Upvotes: 4

Related Questions