Calling a Method Once [closed]

折月煮酒 提交于 2019-12-13 08:22:31

问题


I am having a problem of how to call a method once when the condition achieves many times! for example:

public void onLocaitonChanged(Location location){

  // this if statement may achieve the condition many times
  if(somethingHappened){

       callAMethodOnce();// this method is called once even if the condition achieved again
  }

}

Please help with that


回答1:


public void onLocaitonChanged(Location location){

  // this if statement may achieve the condition many times
  if(somethingHappened){

       if (!isAlreadyCalled){   
           callAMethodOnce();// this method is called once even if the condition achieved again
           isAlreadyCalled = true;
       }
  }

}



回答2:


boolean isHappendBefore = false;

public void onLocaitonChanged(Location location){

  // this if statement may achieve the condition many times

  if(somethingHappened && (! isHappendBefore) ){
       isHappendBefore = true;
       callAMethodOnce();// this method is called once even if the condition achieved again
  }

}



回答3:


You could simply set a flag. If you just need it to only happen once with each instance of the Activity then set a member variable.

public class MyActivity extends Activity
{
     boolean itHappened = false;

     ...

    public void onLocaitonChanged(Location location)
   {

      // this if statement may achieve the condition many times
      if(somethingHappened && !itHappened)
      {
           callAMethodOnce();// this method is called once even if the condition      achieved again
           itHappened = true;
      }   
   }

If you want it to only happen once ever in the life of the application then set that variable as a SharedPreference




回答4:


set a class wide boolean

if(!hasRun){
    callAMethodOnce();
    hasRun = true;
}



回答5:


Maybe I don't understand your question correctly but from your problem definition I would suggest using a boolean variable something like.

boolean run = false;
public void onLocaitonChanged(Location location){

  // this if statement may achieve the condition many times
  if(somethingHappened && run == false){
        run = true;
       callAMethodOnce();// this method is called once even if the condition achieved again
  }

}

Once the code under if statement gets executed once run would be true and there won't be any subsequent calls to callAMethodOnce()



来源:https://stackoverflow.com/questions/20150558/calling-a-method-once

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!