0

I want to get some values from my database, but when I click button (void ButtonClick) my app crashes.

That's my code:

public void ButtonClick() throws Exception {
    getConnection();
}

public Connection getConnection() throws Exception {
    try {
        String username = "*******";
        String password = "*******";
        String url = "jdbc:mysql://http://**.***.***.***:3306/UserDB";
        Class.forName("com.mysql.jdbc.Driver").newInstance();

        Connection conn = (Connection) DriverManager.getConnection(url,username,password);
        Statement statement = (Statement) conn.createStatement();
        String query = "SELECT * FROM TABLE 'UserDB'";
        ResultSet result = statement.executeQuery(query);
        while (result.next()) {
            String name = result.getString("Username");
            int id = result.getInt("ID");
            int points = result.getInt("Points");
            Toast.makeText(this, name + " " + id + " " + points, Toast.LENGTH_SHORT).show();
        }
        return  conn;
    } catch (Exception e) {
        Toast.makeText(this, e.toString(), Toast.LENGTH_SHORT).show();
    }
    return null;
}

(I don't know what's the error because my AVD don't work)

Thanks for help!

T. Maciej
  • 9
  • 4

1 Answers1

1

Starting with Java 7, there is no need to use forName() method. You are creating a new instance in this way and in the same time you are trying to create a connection using DriverManager.getConnection().

So in order to solve this, just remove the instantiation of the driver using forName() method.

Seeing the screen-shot, please note that you can't access a MySQL database from Android natively. Actually you may be able to use JDBC, but it is not recommended. Please see this post

Hope it helps.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
  • 1
    i just ran into this problem. the recommended way for database access is apparently a RESTful service sitting between the app and the database. – 4dc0 Aug 28 '17 at 21:53