Calling the same condition in code

0
//Função para verificar existência de conexão com a internet
public boolean verificaConexao() {  
    boolean conectado;  
    ConnectivityManager conectivtyManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);  
    if (conectivtyManager.getActiveNetworkInfo() != null  
        && conectivtyManager.getActiveNetworkInfo().isAvailable()  
        && conectivtyManager.getActiveNetworkInfo().isConnected()) {  
            conectado = true;  
    } else {  
        conectado = false;  
    }  
    return conectado;  
}

// Verifica a conexao
if (verificaConexao() == true){
    // Chama a classe RequestTask
    new RequestTask().execute(ok);
} else {
    loader.setVisibility(View.GONE);
    tx.setVisibility(View.VISIBLE);
    tx.setText("Por favor, conecte-se a internet :(");
    ba.setVisibility(View.VISIBLE);
}

I want to use this same condition in several places in my code. would I have to do something to call her instead of having to write her all over, every time I need her?

    
asked by anonymous 28.08.2014 / 05:05

2 answers

3

Resolved:

public void conexao() {
    if (verificaConexao() == true){
        // Chama a classe RequestTask
        new RequestTask().execute(site);
    } else {
        loader.setVisibility(View.GONE);
        tx.setVisibility(View.VISIBLE);
        tx.setText("Por favor, conecte-se a internet :(");
        ba.setVisibility(View.VISIBLE);
    }
}

// Verifica a conexao
conexao();
    
29.08.2014 / 06:14
2

Hello

The most educated thing is that you separate responsibilities there.

Predicate<ConnectivityManager> connectionValidator = 
                c -> null != c.getActiveNetworkInfo() 
                    && c.getActiveNetworkInfo().isAvailable() 
                    && c.getActiveNetworkInfo().isConnected();

Then, in the face that you are going to validate the connection, you manipulate the attributes and pass it on.

ConnectivityManager conectivtyManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);  

if (connectionValidator.test(conectivtyManager)){
    new RequestTask().execute(ok);
} else {
    loader.setVisibility(View.GONE);
    tx.setVisibility(View.VISIBLE);
    tx.setText("Por favor, conecte-se a internet :(");
    ba.setVisibility(View.VISIBLE);
}

Of course I assumed here that you will only validate at the class level. If it's something to be used throughout the system, you'd better create a class that implements Predicate and leave the code there. If you're using dependency injection a lot better.

    
28.10.2016 / 14:38