Stackover67
Stackover67

Reputation: 357

How to call a function only after the previous function is fully executed in java

I have a view class which has two methods lets say func1 and func2. In func1 there is a timer of 4 secs. Now when I am accessing these methods in an activity I want to call func2 only after 4secs in func1 gets completed.

Now when I am accessing these in an activity how do I make sure func2 is called only after func1 fully executed. Thanks.

Upvotes: 2

Views: 2302

Answers (5)

Sagar
Sagar

Reputation: 24917

If fun2() should be always executed after timer in fun1() is finished, then simply call it inside onFinsih() method as follows:

 public void func1(){
     new CountDownTimer(4000, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {
            // TODO Auto-generated method stub
        }

        @Override
        public void onFinish() {
          func2();
        }
    }.start();


}

public void func2(){

}

The reason this is good place to call function is, onFinish callback will be fired when the time is up. This will ensure that your intended behavior is achieved.

Upvotes: 2

Sunil Gollapinni
Sunil Gollapinni

Reputation: 169

In java, JRE executes instructions specified in each line sequentially. Here, I see that you have a special requirement because of multi-threading.

Following approaches can be used to tackle this problem:

Option 1:

Call func2() inside onFinish() method which is part of func1(). So that you're sure it is executing after func1() code execution.

    @Override
    public void onFinish() {
      func2();
    }

Option 2:

Since you're setting up the wait time in func1() method, add timer before calling func2() in your calling module.

func1();
setTimeout(function () {
    func2();
}, 5000);

Hope it helps!!

Upvotes: 0

Mayur Patel
Mayur Patel

Reputation: 2326

You can call fun2() in your func1() CountDownTimer method in onFinish().

Like :

    public void func1(){
     new CountDownTimer(4000, 1000) {
                @Override
                public void onTick(long millisUntilFinished) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void onFinish() {
                     func2();
                }
            }.start();
    }

public void func2(){

}

Upvotes: 0

Frans Henskens
Frans Henskens

Reputation: 154

Is this what you're looking for?

public void onFinish() {
    func2();
}

Upvotes: 0

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522094

Would there be anything wrong in calling func2() after the CountDownTimer has finished:

@Override
public void onFinish() {
// TODO Auto-generated method stub
    func2();
}

Actually, this is the only logical place where calling func2() makes sense, because you don't know that the countdown is finished until onFinish() gets called.

Upvotes: 0

Related Questions