java.lang.NullPointerException connecting to Cloud SQL

4.1k Views Asked by At
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.*;

public class ConnectionManager {
    private static String URL  = "jdbc:google:mysql://your-project-id:your-instance-name/database";
    private static String DRIVER = "com.mysql.jdbc.GoogleDriver";
    private static String USERNAME = "root";
    private static String PASSWORD = "test";
    private static Connection CON = null;

    public static Connection getConnection() {
        try {
            Class.forName(DRIVER);
            try {
                CON = DriverManager.getConnection(URL, USERNAME, PASSWORD);
            } catch (SQLException se) {
                //Handle errors for JDBC
                se.printStackTrace();
            }
        } catch (Exception ex) {
            //Handle errors for Class.forName
            ex.printStackTrace();
        }

        //return a connection object
        return CON;
    }

}

I created the above class to connect to my Cloud SQL instance in Android Studio but the above class is returning a NULL which in turn hurts the rest of my code:

conn = ConnectionManager.getConnection();
stmt = conn.createStatement();
String sql;
sql = "INSERT into messages (message) VALUES('Hello World')";
ResultSet rs = stmt.executeQuery(sql);

I'm not sure though why I cam getting this error:

Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'java.sql.Statement java.sql.Connection.createStatement()' on a null object reference

Am I missing some imports or something?

3

There are 3 best solutions below

3
isma3l On BEST ANSWER
com.mysql.jdbc.GoogleDriver

Only works if your app is running in AppEngine,and remember to enable the connector in appengine. If not just use com.mysql.jdbc.Driver.

The guide is very simple: https://cloud.google.com/appengine/docs/java/cloud-sql/#enable_connector_j

1
aw-think On

Found something interesting here: cloud.google.com/sql/docs/external

So you are able to connect with a normal MySQL Connector and without App Engine. You get the jar-file here: http://dev.mysql.com/downloads/connector/j/

To solve 1:

Authorize the IP or range of IPs from which you will be connecting

you need to get your ip. If you on a normal dsl you may get a dynamic ip, so you have to change this often in admin console of Cloud SQL.

0
user2217303 On

This might be a cause of one of two things:

1) Missing permission. Try to add these in the Manifest,

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.access_wifi_state" />

2) Add "jtds-1.3.1.jar" file to app/lib forlder