0

I would call a simple thread in my class but when i call it the application crash. this is the Thread:

private void startGame() {
    new Thread(new Runnable() {
        public void run() {
            while (isGiocoAttivo()) {
                try {
                    Thread.sleep(velocitaDiGioco);
                    accendiBomba();
                } catch (InterruptedException ex) {
                }
            }

        }
    }).start();
}

How can i solve it? The method accendiBomba:

private void accendiBomba() {
    try {
        do {
            this.x = (int) Math.round(Math.random() * (righe - 1));
            this.y = (int) Math.round(Math.random() * (colonne - 1));
        } while (!this.action(this.x, this.y));
    } catch (CampoException ex) {
    }
}
user2520969
  • 1,389
  • 6
  • 20
  • 30
  • 4
    Can you provide some logs from your logcat? Are you performing any UI operation in your method accendiBomba();? – S.A.Norton Stanley Jul 02 '13 at 14:19
  • 2
    post the code of `accendiBomba()` method. guess updating ui from thread. – Raghunandan Jul 02 '13 at 14:21
  • logcat: can't create handler inside thread that has not called Looper.prepare() – user2520969 Jul 02 '13 at 14:26
  • possible duplicate of [Can't create handler inside thread that has not called Looper.prepare()](http://stackoverflow.com/questions/3875184/cant-create-handler-inside-thread-that-has-not-called-looper-prepare) – Simon Jul 02 '13 at 14:27
  • 1
    @user2520969 you are updating ui from backgroudn thread which is not possible use `runOnUiThread` to update ui. – Raghunandan Jul 02 '13 at 14:27
  • Great!! i use runOnUIThread instead of Thread! – user2520969 Jul 02 '13 at 14:35
  • No. `runOnUiThread` is for updating ui . if you want to do back ground computation that can be done in the thread. use `runOnUiThread` iniside the thread if you need to update ui. – Raghunandan Jul 02 '13 at 14:37
  • I must change icon of imageButton, so i must use ronOnUIThread, right? What method can i use to change icon? – user2520969 Jul 02 '13 at 18:11

1 Answers1

0

Do the following within your thread

private void startGame() {
new Thread(new Runnable() {
    public void run() {
        while (isGiocoAttivo()) {
            try {
                Thread.sleep(velocitaDiGioco);
               runOnUiThread(new Runnable() {

                @Override
                public void run() {

                    accendiBomba() 
                }
            });
            } catch (InterruptedException ex) {
            }
        }

    }
}).start();}
S.A.Norton Stanley
  • 1,833
  • 3
  • 23
  • 37