Search code examples
javaandroidandroid-things

I am using handler for delay in android but it's not working


I want a delay for two seconds. and every 2 seconds I want to change the text, and for that, I am using handler like this, but it's not working it's only showing hello. it's not changing at all it only shows what I write second. The code is like this,

      private Handler handler = new Handler();

      int i=5;

      private TextView textView ;



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    textView = (TextView)findViewById(R.id.hello);
    textView.setText("Android Things !!");
    hello_first.run();


}

private Runnable hello_first = new Runnable() {
    @Override
    public void run() {

            textView.setText("Nice Work");
            handler.postDelayed(this,5000);
            textView.setText("Hello");
            handler.postDelayed(this,2000);

            i = i+1;
            if(i==5)
            handler.removeCallbacks(this);
    }
};

Solution

  • You are using postDelayed incorrectly. It looks like you expect it to work the same way Thread.sleep would work. However that is not the case.

    Here is a correct implementation of what you are trying to achieve:

    private Handler handler = new Handler();
    private TextView textView;
    
    private int i = 0;
    private boolean flip;
    
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = (TextView) findViewById(R.id.hello);
        handler.post(hello_first);
    }
    
    private Runnable hello_first = new Runnable() {
        @Override
        public void run() {
                if(++i == 5) {
                    handler.removeCallbacks(this);
                    return;
                }
    
                if(flip) {
                    textView.setText("Nice Work");  
                } else {
                    textView.setText("Hello");
                }
                flip = !flip;
    
                handler.postDelayed(this, TimeUnit.SECONDS.toMillis(2));           
        }
    };