1

I'm trying to execute a Java file, but when I do I get an error NullPointerException in this part of the program.

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

public class HiveClient {
   // JDBC driver required for Hive connections
   private static String driverName = "org.apache.hadoop.hive.jdbc.HiveDriver";
   private static Connection con;

   private static Connection getConnection(String ip, String port, String user, String password) {
      try {
         // dynamically load the Hive JDBC driver
         Class.forName(driverName);
      } catch (ClassNotFoundException e) {
         System.out.println(e.getMessage());
         return null;
      } // try catch

      try {
         // return a connection based on the Hive JDBC driver
         return DriverManager.getConnection("jdbc:hive://" + ip + ":" + port + "/default?user=" + user + "&password=" + password);

      } catch (SQLException e) {
         System.out.println(e.getMessage());
         return null;
      } // try catch
   } // getConnection

   public static void main(String[] args) {
      try {
         // from here on, everything is SQL!
         con = getConnection("130.206.80.46", "10000", "myuser", "mypasswd");
         Statement stmt = con.createStatement();
         ResultSet res = stmt.executeQuery("select column1,column2,otherColumns " + "from mytable where column1='whatever' and columns2 like '%whatever%'");

         // iterate on the result
         while (res.next()) {
            String column1 = res.getString(1);
            Integer column2 = res.getInt(2);

            // whatever you want to do with this row, here
         } // while

         // close everything
         res.close();
         stmt.close();
         con.close();

      } catch (SQLException ex) {
         System.exit(0);
      } // try catch
   }
    // doQuery
} // HiveClient

This is the message:

Exception in thread "main" java.lang.NullPointerException
    at HiveClient.main(HiveClient.java:34)
Java Result: 1

The line the exception is at:

Statement stmt = con.createStatement();

I've checked the java.sql.Connection package and createStatement() is allowed in the Method Summary.

11
  • post your stack trace and add other relevant codes Commented Aug 12, 2014 at 8:53
  • 1
    What does the method getConnection ? The first thing you must do to handle a NPE is track the origin of the null variable. Commented Aug 12, 2014 at 8:53
  • Show your getConnection method. Commented Aug 12, 2014 at 8:55
  • 1
    You probably got no connection, or some driver problems, buy the amount of information You supplied is insufficient. Give us the exception message ad stacktrace. go with: try{ con = getConnection("130.206.80.46", "10000", "myuser", "mypasswd"); Statement stmt = con.createStatement(); } catch(Exception e){ e.printStackTrace(); } Commented Aug 12, 2014 at 8:55
  • Which is line 34 in your code? Commented Aug 12, 2014 at 9:00

7 Answers 7

3

Let's apply some logic to the problem.

Q: Why is the NPE being thrown by that statement?

A: The only possible explanation is that con has the value null.

Q: Why does con have the value null.

A: The only explanation is that this statement is assigning null to con:

        con = getConnection("130.206.80.46", "10000", "myuser", "mypasswd");

And that means that getConnection returns null.

Q: Why is getConnection returning null.

A: Look at the code for that method. There two places where it explicitly returns null. First is when Class.forName(driverName) throws a ClassNotFoundException. Second is when DriverManager.getConnection(...) throws an SQLException. In all other cases, it will return a non-null value. (Read the javadocs ...)

Q: So which is it?

A: Look at the code! Note that in both places where null is returned, you wrote a message to standard output. That message will answer your question!!


The reason you are getting into trouble here is that you are catching exceptions too soon, and returning null as a "remedy". It is that null that is causing the ultimate problem.

The correct way to implement this is to change the declaration for getConnection to say that it throws ClassNotFoundException and SQLException. Then remove the handlers for those exceptions in getConnection and handle them in main instead. And when you do handle them, make sure that you output (or log) the stack traces ... to make it easier to diagnose the real cause of your problems.


(To the authors of some of the other answers: Debugging should not be a matter of guessing what the problem is. You should look at the evidence, and draw logical conclusions from that evidence. When the evidence points to multiple possible causes, consider them all. Guesswork is at best a shortcut. At worst, it will cause you to waste lots of time pursuing "theories" that cannot possibly be true.)

Sign up to request clarification or add additional context in comments.

2 Comments

very nice suggestion for resolving issue (evidence-logical conclusion-multiple causes). Thank you !
What a beautiful explanation! Thank you so much @Stephen!
1

Your getConnection() method should never print out the exception and then return null. It should simply throw an exception, if the driver cannot be found or (for some reason) be successfully loaded. Your code doesn't check at all if the result of getConnection() is null and this would lead to a NullPointerException. What would make sense to check, would be to see if you have the respective JDBC driver on your classpath.

Comments

0

First of all check if your driver is successfully loaded and registered, also check if driver is in your classpath. make it a habit to have a null check before using references like Connection.

4 Comments

hi! in my classpath? I import the package, do I have to download it too?
the location of the XXXdriver.jar should be present in your classpath. if you can import it that means you already have it locally.
since you are not getting ClassNotFoundException for your driver class, it means your driver is in your classpath. try debug and see if you are getting Conncetion reference from DriverManager.getConnection(...)
You're right, the problem is in the driver, because it doesn't go to the first try, it runs catch instead
0

try to get connection using this sway

 DriverManager.getConnection("jdbc:hive://" + ip + ":" + port+ "/default", user, password);

1 Comment

Could you explain what was wrong with OP's code and why this solves the problem?
0

Just to point out what was helpful to me. I added and extra permition to onCreate method of my activity:

if (Build.VERSION.SDK_INT > 9) {
        StrictMode.ThreadPolicy policy = new      StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }

Comments

0

Go to the Database and make sure that first column of your SQLquery is not null. i had same issue because my first column of SQLquery was null in DB. so these exception may occur that first column in your SQLquery is null in DB, and dont try to add null column of DB in SQLquery. i hope this might helped you.

Prabhu MD

Comments

-1

Try something like:

Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql:// localhost:PORT/DBName", "mysql", "mysql");

1 Comment

He is not using mysql.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.