/ / Chiamare un metodo una volta [chiuso] - metodi java, android,

Chiamare un metodo una volta [chiuso] - metodi java, android

Sto avendo un problema su come chiamare un metodo una volta quando la condizione raggiunge molte volte! per esempio:

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
}

}

Per favore aiutaci

risposte:

3 per risposta № 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 per risposta № 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 per risposta № 3

Potresti semplicemente impostare una bandiera. Se hai solo bisogno che accada una sola volta con ogni istanza di Activity quindi impostare una variabile membro.

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

Se vuoi che accada solo una volta nella vita dell'applicazione, imposta quella variabile come a SharedPreference


1 per risposta № 4

imposta un valore booleano di classe

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

1 per risposta № 5

Forse non capisco correttamente la tua domanda, ma dalla tua definizione del problema suggerirei di usare una variabile booleana come qualcosa del genere.

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
}

}

Una volta che il codice sotto if l'istruzione viene eseguita una volta run sarebbe true e non ci saranno chiamate successive a callAMethodOnce()