/ / Appeler une méthode une fois [fermé] - méthodes java, android

Appeler une méthode une fois [fermé] - méthodes java, android

Je ne vois pas comment appeler une méthode une fois que la condition est atteinte plusieurs fois! par exemple:

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
}

}

S'il vous plaît aider avec ça

Réponses:

3 pour la réponse № 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;
}
}

}

3 pour la réponse № 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
}

}

1 pour la réponse № 3

Vous pouvez simplement définir un drapeau. Si vous avez juste besoin que cela se produise une seule fois avec chaque instance du Activity puis définissez une variable membre.

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;
}
}

Si vous voulez que cela n'arrive qu'une fois dans la vie de l'application, définissez cette variable comme SharedPreference


1 pour la réponse № 4

définir une classe large booléen

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

1 pour la réponse № 5

Peut-être que je ne comprends pas bien votre question, mais de votre définition du problème, je suggérerais d'utiliser une variable booléenne quelque chose comme.

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
}

}

Une fois le code sous if déclaration est exécutée une fois run serait true et il n'y aura "pas d'appels ultérieurs à callAMethodOnce()