3

I am trying to make the edittext boxvibrate and change color momentarily if a wrong password is entered

final Drawable oldBackground = findViewById(R.id.email).getBackground();
TimerTask timerTask = new TimerTask() {
    @Override
    public void run() {
        MainActivty.this.findViewById(R.id.password).setBackground(oldBackground);
        MainActivty.this.findViewById(R.id.email).setBackground(oldBackground);
    }
};


Toast.makeText(MainActivty.this , valArray.get(0).toString(), Toast.LENGTH_SHORT).show();
findViewById(R.id.password).setBackgroundColor(Color.RED);
findViewById(R.id.email).setBackgroundColor(Color.RED);
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(500);Timer timer = new Timer();
timer.schedule(timerTask, 1000);
cxzp
  • 652
  • 2
  • 14
  • 28

2 Answers2

7

Timer task runs on a different thread. Ui should be update on the ui thread.

Use runOnUiThread or use a Handler.

          runOnUiThread(new Runnable(){

              @Override
              public void run(){
               // update ui here  
              }
           });

Handler

Handler m_handler;
Runnable m_handlerTask ;  
m_handler = new Handler();   
m_handlerTask = new Runnable()
{
  @Override 
  public void run() { 

    // do something  
    m_handler.postDelayed(m_handlerTask, 1000);    

  }
  };
 m_handlerTask.run();

You can also use a CountDown timer

Countdowntimer in minutes and seconds

Community
  • 1
  • 1
Raghunandan
  • 132,755
  • 26
  • 225
  • 256
5

you must use Timer by runOnUiThread Method Like This:

final TextView lblSSID = (TextView)findViewById(R.id.lblWifiSSID);
    new Timer().scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            runOnUiThread(new TimerTask() {
                @Override
                public void run() {
                    lblSSID.setText(networkConnection.getWifiName());
                }
            });
        }
    }, 0, 5000);
Elyas Nategh
  • 540
  • 6
  • 5