-1

I'm trying to connect a MySQL database using AsyncTask.

I put the MySQL Connection code in AsyncTask as below but it gives me com.mysql.jdbc.CommunicationsExceptionException, How can i resolve it?

MainActivity Class:

public class MainActivity extends ActionBarActivity { 

    private EditText username;
    private EditText password;
    private Button login;
    private TextView loginLockedTV;
    private TextView attemptsLeftTV;
    private TextView numberOfRemainingLoginAttemptsTV;
    int numberOfRemainingLoginAttempts = 3;

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

        username = (EditText) findViewById(R.id.usernameET);
        password = (EditText) findViewById(R.id.passwordET);
        login = (Button) findViewById(R.id.loginBtn);
        loginLockedTV = (TextView) findViewById(R.id.loginLockedTV);
        attemptsLeftTV = (TextView) findViewById(R.id.attemptsLeftTV);
        numberOfRemainingLoginAttemptsTV = (TextView) findViewById(R.id.numberOfRemainingLoginAttemptsTV);
        numberOfRemainingLoginAttemptsTV.setText(Integer.toString(numberOfRemainingLoginAttempts));

        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //new JSONTask().execute("file:///C:/Users/intel/Desktop/details.json");
                new JSONTask().execute(username.getText().toString(),password.getText().toString());
            }
        });
    }

    private class JSONTask extends AsyncTask<String, String, String>{
        @Override
        protected String doInBackground(String... params) {
            Connection con=null;
            PreparedStatement ps=null;
            ResultSet rs=null;
            String count="0";
            try {
                Class.forName("com.mysql.jdbc.Driver");
                con= DriverManager.getConnection("jdbc:mysql://localhost:3306/androidlogin", "root", "root");
                ps=con.prepareStatement("select count(*) from user where username='"+params[0]+"' and password='"+params[1]+"'");
                System.out.println(ps);
                rs=ps.executeQuery();
                while(rs.next()){
                    count=rs.getString(1);
                }
                return count;
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            System.out.println("result: " + result);
            try {
                if (result.equals("1")) {
                    numberOfRemainingLoginAttempts=3;
                    Intent i = new Intent(getApplicationContext(), Main2Activity.class);
                    i.putExtra("username", username.getText().toString());
                    i.putExtra("json",result.split("-")[2]);
                    startActivity(i);

                    Toast.makeText(getApplicationContext(), "Hello admin!", Toast.LENGTH_SHORT).show();
//                    label.setVisibility(View.VISIBLE);
//                    label.setText(result);

                } else {
                    Toast.makeText(getApplicationContext(), "Seems like you 're not admin!", Toast.LENGTH_SHORT).show();
                    numberOfRemainingLoginAttempts--;
                    attemptsLeftTV.setVisibility(View.VISIBLE);
                    numberOfRemainingLoginAttemptsTV.setVisibility(View.VISIBLE);
                    numberOfRemainingLoginAttemptsTV.setText(Integer.toString(numberOfRemainingLoginAttempts));
                }

                if (numberOfRemainingLoginAttempts == 0) {
                    login.setEnabled(false);
                    loginLockedTV.setVisibility(View.VISIBLE);
                    loginLockedTV.setBackgroundColor(Color.RED);
                    loginLockedTV.setText("LOGIN LOCKED!!!");
                }
            } catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(getApplicationContext(), "No Internet Connection!", Toast.LENGTH_SHORT).show();
            }
        }
    }

}

Exceptions at Console:

01-14 12:20:53.494 18010-18060/slv.com.loginapp W/System.err: com.mysql.jdbc.CommunicationsException: Communications link failure due to underlying exception: 
01-14 12:20:53.494 18010-18060/slv.com.loginapp W/System.err: ** BEGIN NESTED EXCEPTION ** 
01-14 12:20:53.494 18010-18060/slv.com.loginapp W/System.err: java.net.SocketException
01-14 12:20:53.494 18010-18060/slv.com.loginapp W/System.err: MESSAGE: java.net.ConnectException: failed to connect to localhost/127.0.0.1 (port 3306) after 90000ms: isConnected failed: ECONNREFUSED (Connection refused)
01-14 12:20:53.494 18010-18060/slv.com.loginapp W/System.err: STACKTRACE:
01-14 12:20:53.494 18010-18060/slv.com.loginapp W/System.err: java.net.SocketException: java.net.ConnectException: failed to connect to localhost/127.0.0.1 (port 3306) after 90000ms: isConnected failed: ECONNREFUSED (Connection refused)
01-14 12:20:53.494 18010-18060/slv.com.loginapp W/System.err:     at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:156)
01-14 12:20:53.494 18010-18060/slv.com.loginapp W/System.err:     at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:284)
01-14 12:20:53.494 18010-18060/slv.com.loginapp W/System.err:     at com.mysql.jdbc.Connection.createNewIO(Connection.java:2565)
01-14 12:20:53.494 18010-18060/slv.com.loginapp W/System.err:     at com.mysql.jdbc.Connection.<init>(Connection.java:1485)
01-14 12:20:53.494 18010-18060/slv.com.loginapp W/System.err:     at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:266)
01-14 12:20:53.494 18010-18060/slv.com.loginapp W/System.err:     at java.sql.DriverManager.getConnection(DriverManager.java:179)
01-14 12:20:53.494 18010-18060/slv.com.loginapp W/System.err:     at java.sql.DriverManager.getConnection(DriverManager.java:213)
01-14 12:20:53.494 18010-18060/slv.com.loginapp W/System.err:     at slv.com.loginapp.MainActivity$JSONTask.doInBackground(MainActivity.java:60)
01-14 12:20:53.494 18010-18060/slv.com.loginapp W/System.err:     at slv.com.loginapp.MainActivity$JSONTask.doInBackground(MainActivity.java:50)
01-14 12:20:53.494 18010-18060/slv.com.loginapp W/System.err:     at android.os.AsyncTask$2.call(AsyncTask.java:288)
01-14 12:20:53.494 18010-18060/slv.com.loginapp W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
01-14 12:20:53.494 18010-18060/slv.com.loginapp W/System.err:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
01-14 12:20:53.494 18010-18060/slv.com.loginapp W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
01-14 12:20:53.494 18010-18060/slv.com.loginapp W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
01-14 12:20:53.494 18010-18060/slv.com.loginapp W/System.err:     at java.lang.Thread.run(Thread.java:818)
01-14 12:20:53.494 18010-18060/slv.com.loginapp W/System.err: ** END NESTED EXCEPTION **
01-14 12:20:53.494 18010-18060/slv.com.loginapp W/System.err: Last packet sent to the server was 123 ms ago.
01-14 12:20:53.495 18010-18060/slv.com.loginapp W/System.err:     at com.mysql.jdbc.Connection.createNewIO(Connection.java:2631)
01-14 12:20:53.495 18010-18060/slv.com.loginapp W/System.err:     at com.mysql.jdbc.Connection.<init>(Connection.java:1485)
01-14 12:20:53.495 18010-18060/slv.com.loginapp W/System.err:     at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:266)
01-14 12:20:53.495 18010-18060/slv.com.loginapp W/System.err:     at java.sql.DriverManager.getConnection(DriverManager.java:179)
01-14 12:20:53.495 18010-18060/slv.com.loginapp W/System.err:     at java.sql.DriverManager.getConnection(DriverManager.java:213)
01-14 12:20:53.495 18010-18060/slv.com.loginapp W/System.err:     at slv.com.loginapp.MainActivity$JSONTask.doInBackground(MainActivity.java:60)
01-14 12:20:53.495 18010-18060/slv.com.loginapp W/System.err:     at slv.com.loginapp.MainActivity$JSONTask.doInBackground(MainActivity.java:50)
01-14 12:20:53.495 18010-18060/slv.com.loginapp W/System.err:     at android.os.AsyncTask$2.call(AsyncTask.java:288)
01-14 12:20:53.495 18010-18060/slv.com.loginapp W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
01-14 12:20:53.495 18010-18060/slv.com.loginapp W/System.err:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
01-14 12:20:53.495 18010-18060/slv.com.loginapp W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
01-14 12:20:53.495 18010-18060/slv.com.loginapp W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
01-14 12:20:53.495 18010-18060/slv.com.loginapp W/System.err:     at java.lang.Thread.run(Thread.java:818)
01-14 12:20:53.495 18010-18010/slv.com.loginapp I/System.out: result: null
01-14 12:20:53.496 18010-18010/slv.com.loginapp W/System.err: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
01-14 12:20:53.499 18010-18056/slv.com.loginapp D/OpenGLRenderer: DisplayEventReceiver 0x5589169500 requestNextVsync
01-14 12:20:53.504 18010-18056/slv.com.loginapp D/OpenGLRenderer: DisplayEventReceiver 0x5589169500 latestVsyncEvent 118270104073235
01-14 12:20:53.509 18010-18010/slv.com.loginapp W/System.err:     at slv.com.loginapp.MainActivity$JSONTask.onPostExecute(MainActivity.java:80)
01-14 12:20:53.509 18010-18010/slv.com.loginapp W/System.err:     at slv.com.loginapp.MainActivity$JSONTask.onPostExecute(MainActivity.java:50)
01-14 12:20:53.509 18010-18010/slv.com.loginapp W/System.err:     at android.os.AsyncTask.finish(AsyncTask.java:632)
Santosh Jadi
  • 1,479
  • 6
  • 29
  • 55

3 Answers3

2

There's two issues here. First off, there's the issue of the hostname. You're telling it to connect to localhost. The database isn't on your phone, so that's the wrong address.

The second- while fixing #1 will make it work, its a bad way to do things. You'd have the password to your database embedded in your app on all your client's phones. That means the password could be trivially decompiled and used. You should not directly connect to a database from any hardware you do not own. Instead you should use a webservice on a machine you control and put it between your db and the phone. Then access the db via webservice. This way the password to your db is never outside of your control.

Gabe Sechan
  • 90,003
  • 9
  • 87
  • 127
  • Im new to android and web services, and im just doing it for practice purpose.. do u have any standard reference code? – Santosh Jadi Jan 14 '16 at 07:34
1

it's the connection string

con= DriverManager.getConnection("jdbc:mysql://localhost:3306/androidlogin", "root", "root");

from the mobile, you need to set the server IP or host-name, not localhost

con= DriverManager.getConnection("jdbc:mysql://MYSQL_SERVER_ADDRESS:3306/androidlogin", "root", "root");

also you need to allow remote connections on mysql-server if it's not already enabled, you need to google that.

Yazan
  • 6,074
  • 1
  • 19
  • 33
0

Should add IP Address of the machine instead of 'localhost', if you are using external physical device.

 con = DriverManager.getConnection("jdbc:mysql://192.168.1.143:3306/ccv", "root", "root");
Santosh Jadi
  • 1,479
  • 6
  • 29
  • 55