0

I am new to android development, and I am trying to create a little game. I have my first CountDownTimer created by the constructor in my GameView subclass of SurfaceView.

What I should do in order to pass on the next level, is call the cancel() of the CountDownTimer class, readapting all the elements for a next level and create a new CountDownTimeragain. I am doing this in the run() of my GameView class that implements Runnable.

I've been reading things through online, but most of the solution are using Activities, as I said, I am working in a subclass of SurfaceView.

This is the error I am receiving

E/AndroidRuntime: FATAL EXCEPTION: Thread-4
              Process: com.example.lucadigiammarino.biogame, PID: 3569
              java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
                  at android.os.Handler.<init>(Handler.java:200)
                  at android.os.Handler.<init>(Handler.java:114)
                  at android.os.CountDownTimer$1.<init>(CountDownTimer.java:114)
                  at android.os.CountDownTimer.<init>(CountDownTimer.java:114)
                  at com.example.lucadigiammarino.biogame.GameCountDownTimer.<init>(GameCountDownTimer.java:0)
                  at com.example.lucadigiammarino.biogame.GameView.startTimer(GameView.java:135)
                  at com.example.lucadigiammarino.biogame.GameView.run(GameView.java:306)
                  at java.lang.Thread.run(Thread.java:761)

Thank you in advance for your time

ldg
  • 450
  • 3
  • 7
  • 27

1 Answers1

0

Thanks to @Roman I manage to solve my problem, the answer is here for a more detailed explanation ---> runOnUiThread inside a View

What I've done I just created a different Thread inside my run() using post(). I repeat that I am in a subclass of SurfaceView.

post(new Runnable() {
    @Override
    public void run() {
        myTimer.cancel;
        startTimer() //creates a new timer
    }
});

Hope it can be helpful for someone else in the future!

Community
  • 1
  • 1
ldg
  • 450
  • 3
  • 7
  • 27