TimerTask error: Looper.prepare () not called

1

I received this error.

  

Can not create handler inside thread that has not called Looper.prepare ()

Aim is to repeat the function that receives the map from 1000 to 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 method OnCreate()

    
asked by anonymous 03.07.2016 / 15:24

1 answer

1

I suppose the problem might be in the recebemapa() method that has code that can only be executed in the UI thread . If so, use the runOnUiThread() method 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 ( maybe better ) is to use a (in this case has to 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);
    
03.07.2016 / 16:06