[HELP] [JAVA]wierd problem
So i coded this application and had it connect to a database that allows external acess, when i compile it it works fine until i put in in an html file then i get
this error
Code:
Exception: com.mysql.jdbc.Driver
java.lang.NullPointerException
at ScoreHandler.loadScore(ScoreHandler.java:52)
at BlockJumper.initRound(BlockJumper.java:60)
at BlockJumper.init(BlockJumper.java:52)
at sun.plugin2.applet.Plugin2Manager$AppletExecutionRunnable.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Exception: java.lang.NullPointerException
heres the source
BlockJumper.java
Code:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import javax.swing.JApplet;
import javax.swing.JOptionPane;
import javax.swing.Timer;
public class BlockJumper extends JApplet implements ActionListener {
private static final long serialVersionUID = -9185143140361183551L;
private BlockDude p1;
private ArrayList<Alien> aliens;
private int frameCount;
private String title = "(click here first) .. ARROWS, SPACE, R, .. GAME_OVER!";
private Timer clock;
private static Image offScreenBuffer;
private Graphics offScreenGraphics;
public static final int EYE_LEVEL = 360;
public String gameNumber = "01";
public int hiScore;
public String hiScoreName = "";
private KeyHandler kh = new KeyHandler(this);
private ScoreHandler record = new ScoreHandler(1);
private String player;
private boolean p1d;
public String getPlayerN(){
return player;
}
public void init() {
getContentPane().setBackground(Color.WHITE);
offScreenBuffer = createImage(getWidth(), getHeight());
offScreenGraphics = offScreenBuffer.getGraphics();
addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
kh.processKeyPress(e.getKeyCode());
}
public void keyReleased(KeyEvent e) {
kh.processKeyRelease(e.getKeyCode());
}
});
initRound();
}
public ScoreHandler getScoreHandler() {
return record;
}
public void initRound() {
record.loadScore();
player = JOptionPane.showInputDialog("Player Name:");
hiScore = record.getLowest();
hiScoreName = record.getLowestName();
p1 = new BlockDude(player, Color.BLUE);
frameCount = 0;
title = title.substring(0, title.length() - 10);
aliens = new ArrayList<Alien>();
clock = new Timer(30, this);
clock.start();
p1d = false;
}
public void paint(Graphics g) {
draw(offScreenGraphics);
g.drawImage(offScreenBuffer, 0, 0, this);
}
public void draw(Graphics g) {
super.paint(g);
g.setColor(Color.BLACK);
g.drawString(title, **** 30);
g.drawRect(0, 0, 7*** 399);
g.setColor(Color.BLACK);
if (!p1d)
p1.draw(g, frameCount);
else
g.drawString(player + " Score:" + frameCount, **** 50);
g.drawString("Lowest High Score: " + hiScore + " - " + hiScoreName,
400, 100);
for (Alien r : aliens) {
r.draw(g);
}
g.drawString(" Top 5 Score:" , **** 100);
g.drawString(record.name[4] + " Score:" + record.high[4] , **** 125);
g.drawString(record.name[3] + " Score:" + record.high[3] , **** 150);
g.drawString(record.name[2] + " Score:" + record.high[2] , **** 175);
g.drawString(record.name[1] + " Score:" + record.high[1] , **** 200);
g.drawString(record.name[0] + " Score:" + record.high[0] , **** 225);
if(frameCount > record.getLowest()) {
g.setColor(Color.RED);
g.drawString("NEW HIGH SCORE!!!", 400, 200);
}
}
public void actionPerformed(ActionEvent e) {
p1.updatePos();
if (Math.random() < 0.05D) {
aliens.add(new Alien(800, 360 - (int) (Math.random() * 40.0D),
(int) (Math.random() * 15.0D), 20, /* Color */new Color(
(int) (Math.random() * 25500) / **** (int) (Math
.random() * 25500) / **** (int) (Math
.random() * 25500) / 100)));
}
for (Alien r : aliens) {
if (p1.getBody().intersects(r)) {
p1d = true;
}
r.x -= r.width;
}
if (p1d) {
kh.gameOver(frameCount);
}
frameCount++;
repaint();
}
public void doRepaint() {
repaint();
}
public BlockDude getBlockDude() {
return p1;
}
public void stopClock() {
clock.stop();
}
public void addTitle(String t) {
title += t;
}
public int getFrameCount() {
return frameCount;
}
public Timer getClock() {
return clock;
}
}
Code:
import java.awt.event.KeyEvent;
public class KeyHandler {
BlockJumper GameFrame;
public KeyHandler(BlockJumper b) {
GameFrame = b;
}
public void processKeyPress(int keyCode) {
// Player 1:
if (keyCode == KeyEvent.VK_LEFT)
GameFrame.getBlockDude().setDirection(-1);
else if (keyCode == KeyEvent.VK_RIGHT)
GameFrame.getBlockDude().setDirection(1);
else if (keyCode == KeyEvent.VK_SPACE)
GameFrame.getBlockDude().jump();
if (keyCode == 80) {
if (GameFrame.getClock().isRunning())
GameFrame.getClock().stop();
else
GameFrame.getClock().start();
}
}
public void gameOver(int p1) {
GameFrame.doRepaint();
GameFrame.stopClock();
GameFrame.addTitle("GAME_OVER!");
if(p1 > GameFrame.getScoreHandler().high[0]){
GameFrame.getScoreHandler().RecordScore(p1, GameFrame.getPlayerN());
}
}
public void processKeyRelease(int keyCode) {
// Player 1
if ((keyCode == 37) && (GameFrame.getBlockDude().getDirection() < 0)) {
GameFrame.getBlockDude().setDirection(0);
} else if ((keyCode == 39)
&& (GameFrame.getBlockDude().getDirection() > 0)) {
GameFrame.getBlockDude().setDirection(0);
} else {
if ((keyCode != 82) || (GameFrame.getClock().isRunning()))
return;
GameFrame.initRound();
}
}
}
ScoreHandler.java
Code:
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.*;
public class ScoreHandler {
private int highScore1;
private int highScore2;
private int highScore3;
private int highScore4;
private int highScore5;
private String Lowestname;
private String Highestname;
private String name1;
private String name2;
private String name3;
private String name4;
private String name5;
public int[] high = new int[5];
public String[] name = new String[5];
private int gamenumber;
private Connection con;
private DatabaseConnection dbcon;
public void RecordScore(int score, String names) {
PreparedStatement ps;
high[0] = score;
name[0] = names;
try {
ps = (PreparedStatement) con.prepareStatement("UPDATE scores SET score1 = ?, score2 = ?, score3 = ?, score4 = ?, score5 = ? WHERE game = " + gamenumber);
for (int i = 1; i <= 5; i++) {
ps.setInt(i, high[i - 1]);
}
ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
try {
ps = (PreparedStatement) con.prepareStatement("UPDATE names SET name1 = ?, name2 = ?, name3 = ?, name4 = ?, name5 = ? WHERE game = " + gamenumber);
for (int i = 1; i <= 5; i++) {
ps.setString(i, name[i - 1]);
}
ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void loadScore() {
PreparedStatement ps;
try {
ps = (PreparedStatement) con.prepareStatement("SELECT * FROM scores WHERE game = " + gamenumber);
ResultSet rs = ps.executeQuery();
if (!rs.next()) {
rs.close();
ps.close();
throw new RuntimeException("Score not found");
}
highScore1 = rs.getInt("score1");
highScore2 = rs.getInt("score2");
highScore3 = rs.getInt("score3");
highScore4 = rs.getInt("score4");
highScore5 = rs.getInt("score5");
PreparedStatement ps2 = (PreparedStatement) con
.prepareStatement("SELECT * FROM names WHERE game = " + gamenumber);
ResultSet rss = ps2.executeQuery();
if (!rss.next()) {
rss.close();
ps2.close();
throw new RuntimeException("Name not found");
}
name1 = rss.getString("name1");
name2 = rss.getString("name2");
name3 = rss.getString("name3");
name4 = rss.getString("name4");
name5 = rss.getString("name5");
int[] h = { highScore1, highScore2, highScore3, highScore4,
highScore5 };
String[] n = { name1, name2, name3, name4, name5 };
sort(h,n);
for (int i = 0; i < h.length; i++) {
if (high[0] == h[i]) {
Lowestname = name[0];
}
}
for (int i = 0; i < h.length; i++) {
if (high[4] == h[i]) {
Highestname = name[i];
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public void sort(int[] a, String[] s) {
for (int n = a.length; n > 1; n--) {
// Find the index iMax of the largest element
// among a[0], ..., a[n-1]:
int iMax = 0;
for (int i = 1; i < n; i++) {
if (a[i] > a[iMax])
iMax = i;
}
// Swap a[iMax] with a[n-1]:
int aTemp = a[iMax];
String nTemp = s[iMax];
a[iMax] = a[n - 1];
s[iMax] = s[n-1];
a[n - 1] = aTemp;
s[n - 1] = nTemp;
// Decrement n (accomplished by n-- in the for loop).
}
high = a;
name = s;
}
public int getLowest() {
return high[0];
}
public int getHighest() {
return high[4];
}
public ScoreHandler(int game) {
dbcon = new DatabaseConnection("url", "user", "pass","dbname");
// dbcon = new DatabaseConnection();
con = dbcon.getConnection();
gamenumber = game;
}
public String getLowestName() {
return Lowestname;
}
public String HighestName() {
return Highestname;
}
public int[] getTop5(){
return high;
}
}
DatabaseConnection.java
Code:
import java.sql.Connection;
import java.sql.DriverManager;
public class DatabaseConnection {
private Connection con;
public DatabaseConnection(String url, String Username , String password, String db) {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection(
"jdbc:mysql://"+url+":3306/"+db+"?autoReconnect=true", Username, password);
} catch (Exception e) {
System.err.println("Exception: " + e.getMessage());
}
}
public DatabaseConnection() {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test?autoReconnect=true", "root", "");
} catch (Exception e) {
System.err.println("Exception: " + e.getMessage());
}
}
public Connection getConnection(){
return con;
}
}
BlockDude.java
Code:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;
public class BlockDude {
private Rectangle body;
private int xVelocity;
private int yVelocity;
private int direction = 0;
private String player;
private Color c;
public BlockDude(String player, Color c) {
body = new Rectangle(200, 320, 20, 40);
xVelocity = (yVelocity = 0);
this.player = player;
this.c = c;
}
public void updatePos() {
int maxVelocity = 8;
if (direction == 1) {
xVelocity += 1;
if (xVelocity > maxVelocity) {
xVelocity = maxVelocity;
}
}
else if (direction == -1)
{
xVelocity -= 1;
if (xVelocity < -maxVelocity)
xVelocity = (-maxVelocity);
}
else if (xVelocity < 0) {
xVelocity += 1;
} else if (xVelocity > 0) {
xVelocity -= 1;
}
body.x += xVelocity;
if (body.x < 0)
body.x = 0;
if (body.x + body.width > 800) {
body.x = (800 - body.width);
}
if (body.y < 360) {
yVelocity -= 1;
body.y -= yVelocity;
if (body.y > 360)
body.y = 360;
}
}
public void draw(Graphics g, int score) {
g.setColor(c);
g.drawString(player + " Score: " + score, body.x, body.y - 5);
g.fillRect(body.x, body.y, body.width, body.height);
}
public void setDirection(int dVal) {
direction = dVal;
}
public int getDirection() {
return direction;
}
public void jump() {
if (body.y < 360)
return;
yVelocity = 15;
body.y -= yVelocity;
}
public Rectangle getBody() {
return body;
}
}
Alien.java
Code:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;
public class Alien extends Rectangle{
private static final long serialVersionUID = 5644048433010974085L;
private Color c;
public Alien(int x, int y, int w, int h, Color c) {
super.x = x;
super.y = y;
super.width = w;
super.height = h;
this.c = c;
}
public void draw(Graphics g) {
g.setColor(c);
g.fillRect(super.x, super.y, super.width, super.height);
}
}
this works fine when compiled in eclipse but get the error when put into html
Re: [HELP] [JAVA]wierd problem
You are probably trying to access an object which hasn't been constructed yet, thus it's pointing to NULL. I don't really know how to work with mysql in java but I would suggest checking the `Connection` and the `PreparedStatement` objects.
It's kind of exhausting to go over the whole code. Have you tried debugging?
Re: [HELP] [JAVA]wierd problem
well it worked when i compiled with eclipse and it ran perfectly so i dont see why there would be a nullpointer exception at all
---------- Post added at 09:00 PM ---------- Previous post was at 08:50 PM ----------
Found out this much if i take out
record.loadScore();
it works
how ever if
i add it back it i get the error