Error trying to connect to a local Mysql database

Asked

Viewed 1,256 times

0

I am having problems trying to access a local Mysql database, I am following this tutorial.

My file MysqlConnect.java:

package br.com.alerts;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;

public class MysqlConnect extends AsyncTask<Void, Void, Boolean> {

    private final static String url = "jdbc:mysql://192.168.0.1:3306/table";
    private final static String user = "root";
    private final static String pass = "159357";
    private Connection con;
    private Context context;
    private ProgressDialog dialog;

    public MysqlConnect(Context context) {
        this.context = context;
    }
    public Boolean isConected() {
        try
        {
            if (con == null)
            {
                return false;
            } else {
                return (!this.con.isClosed());
            } 
        } catch (SQLException e) {
            return false;
        }
    }
    public boolean connect() {
        try
        {
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection(url, user, pass);
            Log.d("","Conectado com sucesso!");
        } catch(Exception e) {
            e.printStackTrace();
        }
        return isConected();
    }
    public void disconnect() {
        try {
            con.close();
            con.isClosed();
            Log.d("","Desconectado!");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        dialog = new ProgressDialog(this.context);
        dialog.setMessage("Aguarde... conectando ao banco de dados...");
        dialog.show();
    }
    @Override
    protected Boolean doInBackground(Void... params) {
        connect();
        return isConected();
    }
    @Override
    protected void onPostExecute(Boolean result) {
        super.onPostExecute(result);
        dialog.dismiss();
    }
}

Class starting the connection, MysqlConnectActivity:

package br.com.alerts;

import java.util.concurrent.ExecutionException;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MysqlConnectActivity extends ActionBarActivity {
    Button btInputHost, btInputPort, btInputDataBase, btInputUser, btInputPassword, btstartConnect;

    String host, port, database, user, password;

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

        btInputHost = (Button) findViewById(R.id.ButtonInputHostConnect);
        btInputPort = (Button) findViewById(R.id.ButtonInputPortConnect);
        btInputDataBase = (Button) findViewById(R.id.ButtonInputDataBaseConnect);
        btInputUser = (Button) findViewById(R.id.ButtonInputUserConnect);
        btInputPassword = (Button) findViewById(R.id.ButtonInputPasswordConnect);
        btstartConnect = (Button) findViewById(R.id.ButtonStartConnect);

        btInputHost.setOnClickListener(new View.OnClickListener() {         
            @Override
            public void onClick(View v) {
                AlertDialog.Builder inputHost = new AlertDialog.Builder(MysqlConnectActivity.this);
                inputHost.setTitle("Host:");

                final EditText et_inputHost = new EditText(MysqlConnectActivity.this);
                inputHost.setView(et_inputHost);

                inputHost.setNeutralButton("Cancelar", null);

                inputHost.setPositiveButton("OK", new DialogInterface.OnClickListener() {                   
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        host = et_inputHost.getText().toString();
                        Toast.makeText(MysqlConnectActivity.this, "Host Entered", Toast.LENGTH_LONG).show();
                    }
                });
                inputHost.show();
            }
        });
        btInputPort.setOnClickListener(new View.OnClickListener() {         
            @Override
            public void onClick(View v) {
                AlertDialog.Builder inputPort = new AlertDialog.Builder(MysqlConnectActivity.this);
                inputPort.setTitle("Port:");

                final EditText et_inputPort = new EditText(MysqlConnectActivity.this);
                inputPort.setView(et_inputPort);

                inputPort.setNeutralButton("Cancelar", null);

                inputPort.setPositiveButton("OK", new DialogInterface.OnClickListener() {                   
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        port = et_inputPort.getText().toString();
                        Toast.makeText(MysqlConnectActivity.this, "Port Entered", Toast.LENGTH_LONG).show();
                    }
                });
                inputPort.show();
            }
        });
        btInputDataBase.setOnClickListener(new View.OnClickListener() {         
            @Override
            public void onClick(View v) {
                AlertDialog.Builder inputDataBase = new AlertDialog.Builder(MysqlConnectActivity.this);
                inputDataBase.setTitle("DataBase:");

                final EditText et_inputDataBase = new EditText(MysqlConnectActivity.this);
                inputDataBase.setView(et_inputDataBase);

                inputDataBase.setNeutralButton("Cancelar", null);

                inputDataBase.setPositiveButton("OK", new DialogInterface.OnClickListener() {                   
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        database = et_inputDataBase.getText().toString();
                        Toast.makeText(MysqlConnectActivity.this, "DataBase Entered", Toast.LENGTH_LONG).show();
                    }
                });
                inputDataBase.show();
            }
        });
        btInputUser.setOnClickListener(new View.OnClickListener() {         
            @Override
            public void onClick(View v) {
                AlertDialog.Builder inputUser = new AlertDialog.Builder(MysqlConnectActivity.this);
                inputUser.setTitle("DataBase:");

                final EditText et_inputUser = new EditText(MysqlConnectActivity.this);
                inputUser.setView(et_inputUser);

                inputUser.setNeutralButton("Cancelar", null);

                inputUser.setPositiveButton("OK", new DialogInterface.OnClickListener() {                   
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        user = et_inputUser.getText().toString();
                        Toast.makeText(MysqlConnectActivity.this, "User Entered", Toast.LENGTH_LONG).show();
                    }
                });
                inputUser.show();
            }
        });
        btInputPassword.setOnClickListener(new View.OnClickListener() {         
            @Override
            public void onClick(View v) {
                AlertDialog.Builder inputPassword = new AlertDialog.Builder(MysqlConnectActivity.this);
                inputPassword.setTitle("DataBase:");

                final EditText et_inputPassword = new EditText(MysqlConnectActivity.this);
                inputPassword.setView(et_inputPassword);

                inputPassword.setNeutralButton("Cancelar", null);

                inputPassword.setPositiveButton("OK", new DialogInterface.OnClickListener() {                   
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        password = et_inputPassword.getText().toString();
                        Toast.makeText(MysqlConnectActivity.this, "Password Entered", Toast.LENGTH_LONG).show();
                    }
                });
                inputPassword.show();
            }
        });
        btstartConnect.setOnClickListener(new View.OnClickListener() {          
            @Override
            public void onClick(View v) {           
                MysqlConnect con = new MysqlConnect(MysqlConnectActivity.this);

                TextView tvText = (TextView) findViewById(R.id.ButtonTextTest);
                tvText.setText("Aguardando...");

                try {
                    if (con.execute().get()){
                        if (con.isConected())
                        {
                            tvText.setText("Conectado!");
                        } else {
                            tvText.setText("Falha na Conexao!");
                        }               
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}

And my Logcat:

02-14 22:18:16.352: W/System.err(3822): java.sql.SQLException: Unable to connect to any hosts due to exception: java.net.SocketException: java.net.ConnectException: failed to connect to /192.168.0.1 (port 3306): connect failed: ETIMEDOUT (Connection timed out)
02-14 22:18:16.353: W/System.err(3822): ** BEGIN NESTED EXCEPTION ** 
02-14 22:18:16.353: W/System.err(3822): java.net.SocketException
02-14 22:18:16.353: W/System.err(3822): MESSAGE: java.net.ConnectException: failed to connect to /192.168.0.1 (port 3306): connect failed: ETIMEDOUT (Connection timed out)
02-14 22:18:16.353: W/System.err(3822): STACKTRACE:
02-14 22:18:16.354: W/System.err(3822): java.net.SocketException: java.net.ConnectException: failed to connect to /192.168.0.1 (port 3306): connect failed: ETIMEDOUT (Connection timed out)
02-14 22:18:16.354: W/System.err(3822):     at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:143)
02-14 22:18:16.354: W/System.err(3822):     at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:225)
02-14 22:18:16.509: W/System.err(3822):     at com.mysql.jdbc.Connection.createNewIO(Connection.java:1805)
02-14 22:18:16.509: W/System.err(3822):     at com.mysql.jdbc.Connection.<init>(Connection.java:452)
02-14 22:18:16.549: W/System.err(3822):     at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:411)
02-14 22:18:16.549: W/System.err(3822):     at java.sql.DriverManager.getConnection(DriverManager.java:179)
02-14 22:18:16.549: W/System.err(3822):     at java.sql.DriverManager.getConnection(DriverManager.java:213)
02-14 22:18:16.551: W/System.err(3822):     at br.com.alerts.MysqlConnect.connect(MysqlConnect.java:41)
02-14 22:18:16.551: W/System.err(3822):     at br.com.alerts.MysqlConnect.doInBackground(MysqlConnect.java:66)
02-14 22:18:16.551: W/System.err(3822):     at br.com.alerts.MysqlConnect.doInBackground(MysqlConnect.java:1)
02-14 22:18:16.552: W/System.err(3822):     at android.os.AsyncTask$2.call(AsyncTask.java:288)
02-14 22:18:16.552: W/System.err(3822):     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
02-14 22:18:16.552: W/System.err(3822):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
02-14 22:18:16.552: W/System.err(3822):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
02-14 22:18:16.554: W/System.err(3822):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
02-14 22:18:16.554: W/System.err(3822):     at java.lang.Thread.run(Thread.java:818)
02-14 22:18:16.617: W/System.err(3822): ** END NESTED EXCEPTION **
02-14 22:18:16.618: W/System.err(3822):     at com.mysql.jdbc.Connection.createNewIO(Connection.java:1875)
02-14 22:18:16.619: W/System.err(3822):     at com.mysql.jdbc.Connection.<init>(Connection.java:452)
02-14 22:18:16.619: W/System.err(3822):     at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:411)
02-14 22:18:16.619: W/System.err(3822):     at java.sql.DriverManager.getConnection(DriverManager.java:179)
02-14 22:18:16.619: W/System.err(3822):     at java.sql.DriverManager.getConnection(DriverManager.java:213)
02-14 22:18:16.619: W/System.err(3822):     at br.com.alerts.MysqlConnect.connect(MysqlConnect.java:41)
02-14 22:18:16.620: W/System.err(3822):     at br.com.alerts.MysqlConnect.doInBackground(MysqlConnect.java:66)
02-14 22:18:16.620: W/System.err(3822):     at br.com.alerts.MysqlConnect.doInBackground(MysqlConnect.java:1)
02-14 22:18:16.620: W/System.err(3822):     at android.os.AsyncTask$2.call(AsyncTask.java:288)
02-14 22:18:16.620: W/System.err(3822):     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
02-14 22:18:16.620: W/System.err(3822):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
02-14 22:18:16.621: W/System.err(3822):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
02-14 22:18:16.621: W/System.err(3822):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
02-14 22:18:16.621: W/System.err(3822):     at java.lang.Thread.run(Thread.java:818)
02-14 22:18:16.639: I/Choreographer(3822): Skipped 7071 frames!  The application may be doing too much work on its main thread.
02-14 22:18:17.890: I/Choreographer(3822): Skipped 110 frames!  The application may be doing too much work on its main thread.

Mysql is running on my machine on port 3606, now I do not know if there is a firewall and if Mysql is enabled to receive external connection.

How can I solve this problem?

  • 1

    Have you checked if Mysql is running? Is there a firewall running on the server? Is your Mysql running on the same network as your Android? Is your Mysql configured to receive external connections? Is your Mysql listening on port 3306? If you can edit your question and report all this it is easier to locate the problem.

1 answer

1

Configure your Database according to this tutorial:

#1 – Edite o arquivo: 
sudo nano /etc/mysql/my.cnf
#2 – Altere a seguinte linha:
#bind-address = 127.0.0.1
#Deixando assim:
#bind-address = 0.0.0.0
#3 – Reinicie o Mysql
sudo /etc/init.d/mysql restart
#4 – Vamos agora dar GRANT no usuário root, logue no mysql:
mysql -u root -p
#5 – Após se logar, digite o seguinte comando:
GRANT ALL ON *.* TO root@’%’ IDENTIFIED BY ‘sua_senha’;

If you can’t find the configuration file, find it by cmd/terminal

use find -name 'my.cnf' in a Unix environment

use dir my.cnf /s"

Source: enabling-remote access

If it does not work, there is the possibility of your internet provider to provide some kind of lock ports, in the case of netvirtual for example it is not possible to withdraw, if you need to test on a different network, use some service like the AWS you can use a set of services for free for one year.

If you want to test with your phone on the same network, it is still possible, leave your phone on wifi and turn off 3G, if it does not work your router is blocked port, enter the configuration page of your router (if using linux find the ip using route -n) open port 3606 and test again.

Links to Mysql installation Windows,Linux

  • Dude, I’m starting to think I made a mistake trying to install Mysql on my machine, I started Mysql Comunity that I got on Mysql site, this right?

  • Yes, if you are using Windows, go to the folder c: Windows my.ini or c: my.cnf, and follow the same steps as the tutorial, don’t forget to restart mysql.

  • I’m sorry but could you give me a tutorial on how to install Mysql? I had no success searching for these two folder that Oce quoted above @Isvaldo Fernandes

  • I updated the question by placing links to install in windows

  • I tried to do this, only that I couldn’t locate my.ini or my.cnf files, I’m using version 5.6...

  • 1

    How do I locate this information? URL: jdbc:mysql://<ip>:<port>/<database>";

Show 1 more comment

Browser other questions tagged

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