Exception in thread & ldquo; hand & rdquo; java.lang.NullPointerException in java when converting to MYSQL

advertisements

I am a beginner in Java and I am writing a code to input json twitter datasets into MYSQL database. I used a file name "file" as an input, parse it, and write it to SQL database. However, I keep getting the error:

Exception in thread "main" java.lang.NullPointerException at edu.mbhs.twitter.test.main(test.java:42)

Line 42 contains:

  if (tweet.getLang().equals("en")){

Here is my main class code:

public class test {

public static List <String> list = new ArrayList<String>();

public static void main(String[] args) throws FileNotFoundException, InterruptedException, SQLException {

    JSONParser j = new JSONParser(new File("file"));
    ArrayList<Tweet> tweets = j.getTweets();

   String sql = "insert into twitterdatasets (tweet_created_at, tweet_id, tweet_text, user_id, user_screen_name, user_location, user_followers_count, user_friends_count, user_created_at, user_verified, user_lang, tweet_retweeted_count, tweet_favorite_count, tweet_lang) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
   Connection conn = getConnection();
   PreparedStatement ps = conn.prepareStatement(sql);

   final int batchSize = 1000;
   int count = 0;

   for (Tweet tweet: tweets){

       if (tweet.getLang().equals("en")){
           User user = tweet.getUser();
           ps.setString(1, tweet.getCreatedAt());
           ps.setString(2, tweet.getIdStr());
           ps.setString(3, tweet.getText());
           ps.setString(4, user.getIdStr());
           ps.setString(5, user.getScreenName());
           ps.setString(6, user.getLocation());
           ps.setInt(7, user.getFollowersCount());
           ps.setInt(8, user.getFriendsCount());
           ps.setString(9, user.getCreatedAt());
           ps.setBoolean(10, user.getVerified());
           ps.setString(11, user.getLang());
           ps.setInt(12, tweet.getRetweetCount());
           ps.setInt(13, tweet.getFavoriteCount());
           ps.setString(14, tweet.getLang());
           ps.addBatch();
       if (++count % batchSize == 0){
           ps.executeBatch();
       }

       }
   }

   ps.executeBatch();
   ps.close();
   conn.close();
   System.out.println("File has been successfully written to database");
}

private static Connection getConnection() {
      Connection con = null;
      String url = "jdbc:mysql://localhost:3306/";
      String db =  "dbo";
      String driver = "com.mysql.jdbc.Driver";
      String user = "root";
      String pass = "elvira03";
      try {
       Class.forName(driver);
       con = DriverManager.getConnection(url + db, user, pass);
      } catch (ClassNotFoundException e) {
       e.printStackTrace();
      } catch (SQLException e) {
       e.printStackTrace();
      }
      return con;
     }
}


Try

if(tweet.getLang()!= null && tweet.getLang().equals("en") { ... }

I think in some tweets language can be null if user didnt set it.