Prerit Mohan
Prerit Mohan

Reputation: 528

Android -Timer concept

Sorry for asking such a basic question, Actually i need to call a method after certain time interval which is actually assigning a text to textView in android,which is supposed to change.So please suggest me the best way to do this. Thanking you in anticipation.

{
         int splashTime=3000;
         int waited = 0;
         while(waited < splashTime)
         {
             try {
                  ds.open();
                  String quotes=ds.getRandomQuote();
                  textView.setText(quotes);
                  ds.close();


              }
              catch(Exception e)
              {
                  e.printStackTrace();
              }
         }
         waited+=100;
     }

Upvotes: 1

Views: 187

Answers (3)

phnom
phnom

Reputation: 33

Use a handler and put it in a Runnable:

int splashTime = 3000;
Handler handler = new Handler(activity.getMainLooper());
handler.postDelayed(new Runnable() {
    @Override
    public void run() {
        try {
            ds.open();
            String quotes=ds.getRandomQuote();
            textView.setText(quotes);
            ds.close();
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
}, splashTime);

Upvotes: 1

Berť&#225;k
Berť&#225;k

Reputation: 7322

you can use Timer to update your UI with delay like this:

    long delayInMillis = 3000; // 3s
    Timer timer = new Timer();
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            // you need to update UI on UIThread
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    ds.open();
                    String quotes=ds.getRandomQuote();
                    textView.setText(quotes);
                    ds.close();
                }
            });
        }
    }, delayInMillis);

Upvotes: 1

slezadav
slezadav

Reputation: 6141

Have you considered CountDownTimer ? For example something like this:

     /**
     * Anonymous inner class for CountdownTimer
     */
    new CountDownTimer(3000, 1000) { // Convenient timing object that can do certain actions on each tick

        /**
         * Handler of each tick.
         * @param millisUntilFinished - millisecs until the end
         */
        @Override
        public void onTick(long millisUntilFinished) {
            // Currently not needed
        }

        /**
         * Listener for CountDownTimer when done.
         */
        @Override
        public void onFinish() {
             ds.open();
              String quotes=ds.getRandomQuote();
              textView.setText(quotes);
              ds.close(); 
        }
    }.start();

Of course, you can put it in a loop.

Upvotes: 4

Related Questions