Error in Mysql connection and Android application

Asked

Viewed 385 times

2

I’m having an error trying to make the connection between my App and the Mysql database.

I am creating a direct connection to my bank, I know the best way would be to use a webservice, but I am making this connection in localhost and I don’t have much knowledge in webservice.

I’m using my own mobile to run the application. Below is the code.

Register Class:

package com.example.junior.fireflyapp;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.InputType;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.wdullaer.materialdatetimepicker.date.DatePickerDialog;
import com.wdullaer.materialdatetimepicker.time.RadialPickerLayout;
import com.wdullaer.materialdatetimepicker.time.TimePickerDialog;

import java.util.Calendar;

public class ActCadastro extends AppCompatActivity implements DatePickerDialog.OnDateSetListener, TimePickerDialog.OnTimeSetListener, DialogInterface.OnCancelListener{

private Usuario usuario;

//EditText
private EditText txtNome;
private EditText txtSobrenome;
private EditText txtDtNasc;
private EditText txtEmail;
private EditText txtSenha;
private String sexo;

//RadioButton
private RadioGroup rdgSexo;
private RadioButton rbtMasculino;
private RadioButton rbtFeminino;

//Button
private Button btnCadastrar;

//CheckBox
private CheckBox cbxTermosUso;


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

    this.usuario = new Usuario();


    this.txtNome = (EditText)findViewById(R.id.txtNome);
    this.txtSobrenome = (EditText)findViewById(R.id.txtSobrenome);
    this.txtDtNasc = (EditText)findViewById(R.id.txtDtNasc);
    this.txtDtNasc.setInputType(InputType.TYPE_NULL);
    this.txtEmail = (EditText)findViewById(R.id.txtEmail);
    this.txtSenha = (EditText)findViewById(R.id.txtSenha);


    this.rdgSexo = (RadioGroup)findViewById(R.id.rdgSexo);
    this.rbtMasculino = (RadioButton)findViewById(R.id.rbtMasculino);
    this.rbtFeminino = (RadioButton)findViewById(R.id.rbtFeminino);


    this.btnCadastrar = (Button)findViewById(R.id.btnCadastrar);

    this.cbxTermosUso = (CheckBox)findViewById(R.id.cbxTermosUso);

    txtDtNasc.setOnClickListener(new View.OnClickListener(){

        @Override
        public void onClick(View v) {
            scheduleTestDrive(v);
        }
    });
    }

private int day, month, year;

private void scheduleTestDrive(View v) {
    InitDateTimeData();
    Calendar cDefault = Calendar.getInstance();
    cDefault.set(year, month,day);

    DatePickerDialog datePickerDialog = DatePickerDialog.newInstance(
        this,
        cDefault.get(Calendar.YEAR),
        cDefault.get(Calendar.MONTH),
        cDefault.get(Calendar.DAY_OF_MONTH)
    );

    datePickerDialog.setOnCancelListener(this);
    datePickerDialog.show(getFragmentManager(),"DatePickerDialog");
}

private void InitDateTimeData(){
    if (year == 0){
        Calendar c = Calendar.getInstance();
        year = c.get(Calendar.YEAR);
        month = c.get(Calendar.MONTH);
        day = c.get(Calendar.DAY_OF_MONTH);
    }
}


public void onClickCadastrar(View view){

    boolean selectSexo;

    if (rbtMasculino.isChecked()){
       selectSexo = R.id.rbtMasculino == rdgSexo.getCheckedRadioButtonId();
       sexo = "M";
    }else {
        selectSexo = R.id.rbtFeminino == rdgSexo.getCheckedRadioButtonId();
        sexo = "F";
    }


    if(txtNome.getText().toString().isEmpty() ||
       txtSobrenome.getText().toString().isEmpty() ||
       txtDtNasc.getText().toString().isEmpty() ||
       txtEmail.getText().toString().isEmpty() ||
       txtSenha.getText().toString().isEmpty() ||
       !selectSexo)
    {
        Toast.makeText(getApplicationContext(),"Todos os campos são obrigatórios", Toast.LENGTH_SHORT).show();

    }else if(!cbxTermosUso.isChecked())
    {

        Toast.makeText(getApplicationContext(),"Para prosseguir você precisa aceitar os termos de uso", Toast.LENGTH_SHORT).show();

    }else if(txtSenha.length() < 6 || txtSenha.length() > 12)
    {

        Toast.makeText(getApplicationContext(),"Sua senha deve ter entre 6 e 12 caracteres.", Toast.LENGTH_SHORT).show();

    }else
    {
            this.usuario.setNome(this.txtNome.getText().toString());
            this.usuario.setSobrenome(this.txtSobrenome.getText().toString());
            this.usuario.setDataNascimento(this.txtDtNasc.getText().toString());
            this.usuario.setEmail(this.txtEmail.getText().toString());
            this.usuario.setSenha(this.txtSenha.getText().toString());
            this.usuario.setSexo(sexo);
            this.usuario.setDataNascimento(this.txtDtNasc.getText().toString());

            this.usuario.cadastrar();

            Toast.makeText(this, this.usuario.get_mensagem(), Toast.LENGTH_LONG).show();

            if(usuario.is_status())
                finish();
    }
}

@Override
public void onCancel(DialogInterface dialog) {
     year = month = year = 0;
     txtDtNasc.setText("");
}

@Override
public void onDateSet(DatePickerDialog view, int y, int m, int d) {
    year = y;
    month = m;
    day = d;

    txtDtNasc.setText((day < 10 ? "0" + day : day) + "/" + (month+1 < 10 ? "0" + (month + 1) : (month+1)) + "/" + year);
}

@Override
public void onTimeSet(RadialPickerLayout view, int hourOfDay, int minute) {

}
}

Connection class:

package com.example.junior.fireflyapp;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;


public class DB extends _Default implements Runnable {

private Connection conn;
private String host = "127.0.0.1";
private String db = "dbAppFireFly";
private int port = 3306;
private String user = "root";
private String pass = "junior3xtreme92";
private String url = "jdbc:mysql://%s:%d/%s";

public DB() {
    super();
    this.url = String.format(this.url, this.host, this.port, this.db);

    this.conectar();
    this.desconectar();
    }

@Override
public void run() {
    try{

        Class.forName("com.mysql.jdbc.Driver");
        this.conn = DriverManager.getConnection(this.url, this.user, this.pass);
    }catch(Exception e){
        this._mensagem = e.getMessage();
        this._status = false;
    }
}

private void conectar(){

    Thread tread = new Thread(this);
    tread.start();
    try{
        tread.join();//Aplicação espera a conclusão do metodo run

    }catch (Exception e){
        this._mensagem = e.getMessage();
        this._status = false;
    }

}

private void desconectar(){

    if(this.conn != null){
        try{
            this.conn.close();
        }catch(Exception e){

        }finally {
            this.conn = null;
        }
    }

}

public ResultSet select(String query){
   this.conectar();
    ResultSet resultSet = null;
    try {
        resultSet = new ExecuteDB(this.conn, query).execute().get();
    }catch (Exception e){
        this._status = false;
        this._mensagem = e.getMessage();
    }

    return resultSet;
}

public ResultSet executar(String query) {
    this.conectar();
    ResultSet resultSet = null;
    try {
        resultSet = new ExecuteDB(this.conn, query).execute().get();
    } catch (Exception e) {
        this._status = false;
        this._mensagem = e.getMessage();
    }

    return resultSet;
}
 }

Follow also my Radle:app

apply plugin: 'com.android.application'

android {
compileSdkVersion 23
buildToolsVersion "23.0.2"
defaultConfig {
    applicationId "com.example.junior.fireflyapp"
    minSdkVersion 16
    targetSdkVersion 23
    versionCode 1
    versionName "1.0"
    multiDexEnabled true

}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
productFlavors {
}
}

dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
compile 'com.android.support:appcompat-v7:23.1.1'
compile 'com.android.support:design:23.1.1'
compile 'mysql:mysql-connector-mxj:5.0.12'
compile 'com.wdullaer:materialdatetimepicker:1.4.1'
//compile 'mysql:mysql-connector-java:5.1.37'
}

The error is being shown in the method run of the connection class on the following line.

this.conn = DriverManager.getConnection(this.url, this.user, this.pass);

After this line, the App gives a exception with the following message:

com.mysql.jdbc.exceptions.jdbc4.Communicationsexception: Communications link Failure
The last Packet sent successfully to the server was 0 milliseconds ago. The driver has not Received any packets from the server.

  • You can’t (or at least shouldn’t) connect a direct android device to a database without interacting with an API.

  • Androiderson, I am using my mobile device, because the emulator of Android Studio does not work on my pc, from what I have read, it is because my processor is AMD and not Intel. When I try to emulate by AVD, Android Studio gives me a message saying that HAXM is not installed, but in my SDK Manager is listed as installed.

2 answers

1


I believe that for this to work your Mysql Driver should exist within your android OS. Generally we use webservices as intermediaries. I recommend the use of restful WS.

  • Anderson, could you point me to some link so I can create this web service?

  • Maurício, if you want to do in java I suggest using Jersey, which is an implementation of JAX-RS. There is a lot of material on the internet on the subject. Here’s one I found: http://www.devmedia.com.br/desenvolvendo-web-services-restful-utilizando-a-api-jax-rs-2-0-e-jersey/27141.

0

Mauricio, I advise you to use an API to connect to the bank and remove the app’s responsibility for this. Create a Rest API, Spring-boot makes it a lot easier and a client to connect with these guys. Use the standard Microservices for this specific case and for the client I advise the Netflix Feign.

Build a Restful web server

Feign Client

  • Good afternoon @Fernandosoliva. Welcome to Stackoverflow. Would you kindly show us how the Rest API is made?

  • Hi @Danilo, thanks for the welcome. I left the links in the comment above that exemplifies both the creation of the Rest API and the creation of a Client.

  • This is just a hint for the next answers :D

  • @Fernandosoliva. Thanks for the tips. As soon as I can test, I return here.

Browser other questions tagged

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