user2275917
user2275917

Reputation: 1

I am using handler to call a function after few seconds but its not working

I am trying to call a method after a period of 5 seconds. I have written this code in OnCreate function but it runs only once. What am I doing wrong ?

new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
        @Override
        public void run() {
            getData();
        }
    }, 5000);

Upvotes: 0

Views: 421

Answers (1)

Gabe Sechan
Gabe Sechan

Reputation: 93561

Because Handlers only run messages once. If you want it to post multiple times (each with a 5 second delay), you need to do something like this:

final Handler handler = new Handler(Looper.getMainLooper);
handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            getData();
            handler.postDelayed(this, 5000);
        }
    }, 5000);

This reposts the same runnable with a new delay when its done running once.

Upvotes: 1

Related Questions