Check Connection to bank and validate to user

Asked

Viewed 434 times

2

I would like to know the following: I am trying to make an application that makes several connections to the database. I always wanted to check the connections and if the connection is not available alert the user and terminate the method running..

For example: When using Connection = DriverManager.getConnection() and test the connection, if it was successfully performed continues the method, otherwise for execution and sends an alert to the user!

Any idea?

1 answer

0


Taking a look at the Drivermanager documentation, we can see that if something goes wrong while running getConnection(), a Sqlexception exception will be released.

So try to do the following:

try {
    Connection connection = DriverManager.getConnection();
    // continua a execução

} catch(SQLException e){
    // algo deu errado, mostrar o erro no Log de execução
    e.printStackTrace();
    // aqui você pode tratar a exceção e dizer ao usuário que algo deu errado
}

I recommend you take a look here too: Documentation Drivermanager from Android

A possible implementation with Asynctask is as follows:

public class ConnectActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        connect();
    }

    private void connect(){
        new HandleConnection(this).execute();
    }

    public void getConnectionResponse(String response){
        if(response.equals("SUCCESS")){
            // prosseguir com o procedimento depois da conexão
            actionAfterConnection();
        } else {
            // exibir alerta de erro na conexão
            showAlertConnectionFailed();
        }
    }

    private void actionAfterConnection(){

    }

    private void showAlertConnectionFailed(){

    }
}

Above we have the Activity that will call the Asynctask Handleconnection via the connect method().

Now, the Handleconnection class:

public class HandleConnection extends AsyncTask<Void, Void, String> {
    ProgressDialog progressDialog;
    ConnectActivity connectActivity;

    public HandleConnection(ConnectActivity connectActivity){
        progressDialog = new ProgressDialog(connectActivity);
        progressDialog.setTitle("Carregando...");
        progressDialog.setCancelable(false);
        progressDialog.show();

        this.connectActivity = connectActivity;
    }

    @Override
    protected String doInBackground(Void... params) {
        try {
            Connection connection = DriverManager.getConnection("suaconexao");

            return "SUCCESS";
        } catch(SQLException e){
            e.printStackTrace();

            return "FAIL";
        }
    }

    protected void onPostExecute(String connectionResponse){
        super.onPostExecute(connectionResponse);
        try {
            progressDialog.dismiss();

            connectActivity.getConnectionResponse(connectionResponse);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

In the Handleconnection class constructor we ask for an instance of Activity Connectionactivity, which is the class that calls Asynctask. Since we have the instance of an Activity, we can use its context to create a Progressdialog, which is that window indicating that an action is being executed and the user must wait.

In the Asynctask InBackground method, we checked whether the connection was successful or if something went wrong. If something goes wrong, the "catch" block will be called and the method will return "FAIL". Otherwise, it will return "SUCCESS".

In the onPostExecute method, we get the return of theInBackground and pass the value to the Activity Connectionactivity through the getConnectionResponse() method. Thus, the result of the operation will be visible in Activity. Now that you have the connection information, you can alert the user if the connection fails. Just create your Alertdialog in Activity’s showAlertConnectionFailed() method.

  • 1

    The catch won’t let me run Alertdialog on a background thread.... even though I run a Trows in catch to manipulate it later... The issue is much more complex than that!!! I wanted the idea of a validation that works in trheads, asynctasks and similar, especially in background executions

  • I get your point. To display some kind of Dialog in threads or Asynctasks, you need to pass the context(Context) of an Activity. I believe that to be able to catch a failure in the connection, you should use catch with Sqlexception itself. There are other ways to get an answer in the Activity class to know how to proceed. I will edit the answer and you take a look.

  • beauty, I’m waiting for Edit

Browser other questions tagged

You are not signed in. Login or sign up in order to post.