Execute function after 5 seconds in Android

Solution 1:

You can use the Handler to add some delay.Call the method displayData() as below so that it will be executed after 5 seconds.

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

Note : Do not use the threads like Thread.sleep(5000); because it will block your UI and and makes it irresponsive.

Solution 2:

Assign millisDelayTime variable with the milliseconds you desire to cause a delay. mActivity is an object of Activity for providing Application Context. In your case millisDelayTime should be initialized with 5000

mActivity.runOnUiThread(new Runnable() {
@Override
    public void run() {
    final Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
       @Override
       public void run() {
             //your code here
       }
    }, millisDelayTime);
  }
});

Solution 3:

Use a CountDownTimer

// There's a TextView txtCount in Main Activity

final int secs = 5;
new CountDownTimer((secs +1) * 1000, 1000) // Wait 5 secs, tick every 1 sec
{
    @Override
    public final void onTick(final long millisUntilFinished)
    {
        txtCount.setText("" + (int) (millisUntilFinished * .001f));
    }
    @Override
    public final void onFinish()
    {
        txtCount.setText("GO!");
        finish();
        // Time's up - Start the Login Activity
        final Intent tnt =
            new Intent(getApplicationContext(), LoginActivity.class);
        startActivity(tnt);
    }
}.start();

Solution 4:

Try this, code create CountDownTimer with one tick

timer = new CountDownTimer(5000, 5000)
{
    public void onTick(long millisUntilFinished)
    {
    }

    public void onFinish()
    {
        displayData();
    }
};
timer.start();