Timertask Error: Looper.prepare() not called

Asked

Viewed 176 times

1

I got this mistake.

Can’t create Handler Inside thread that has not called Looper.prepare()

The goal is to repeat the function that receives the map every 1000 thousandths of a second.

Timer t = new Timer();
//Set the schedule function and rate
        t.scheduleAtFixedRate(new TimerTask() {

                                  @Override
                                  public void run() {
                                      try {
                                          recebemapa();
                                      } catch (UnsupportedEncodingException e) {
                                          e.printStackTrace();
                                      }
                                  }

                              },
//Set how long before to start calling the TimerTask (in milliseconds)
                0,

//Set the amount of time between each execution (in milliseconds)
                1000);

I call this code in the method OnCreate()

  • The method recebemapa() access methods of any View?

  • Yes you have access to methods.

1 answer

1


I suppose the problem might be in the method recebemapa() have code that can only be executed on UI thread.
If so use the method runOnUiThread() to execute this code:

Timer t = new Timer();
t.scheduleAtFixedRate(new TimerTask() {

      @Override
      public void run() {
              runOnUiThread(new Runnable()
              {
                  public void run()
                  {
                      try {
                          recebemapa();
                      } catch (UnsupportedEncodingException e) {
                          e.printStackTrace();
                      }
                  }
              });
      }

 },0, 1000);  

An alternative(perhaps better) is to use a Handler(in this case it must be created in the UI Thread, which is the case of onCreate())

final Handler handler = new Handler();

Runnable runnable = new Runnable() {
    @Override
    public void run() {
        try {
            recebemapa();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        handler.postDelayed(this, 1000);
    }
};
handler.postDelayed(runnable, 0);
  • Was exactly this was the function to fetch the server json already solved thank you

Browser other questions tagged

You are not signed in. Login or sign up in order to post.