Java Null pointer exception [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
We are trying to display information in a textarea from a database table.
public void displayEmployees()
{
String sqlDisplayQuery ="";
sqlDisplayQuery+= "Select * from JAVAUSER.Employee";
System.out.println(sqlDisplayQuery);
Driver.sendDBCommand(sqlDisplayQuery);
try
{
while (dbResults.next())
{
int employeeID= dbResults.getInt(1);
String employeeFName = dbResults.getString(2);
String employeeLName = dbResults.getString(3);
System.out.println("Employee " +employeeID + employeeFName + employeeLName);
txtaOutput.appendText("Employee" +employeeID + employeeFName + employeeLName);
}
}
catch (SQLException e)
{
System.out.println(e.toString());
}
}
public static boolean isNumeric(String string)
{
try
{
double num = Double.parseDouble(string);
}
catch(NumberFormatException e)
{
return false;
}
return true;
}
public static void sendDBCommand(String sqlQuery)
{
String URL = "jdbc:oracle:thin:#localhost:1521:XE";
String userID = "javauser";
String userPASS = "javapass";
OracleDataSource ds;
try
{
ds = new OracleDataSource();
ds.setURL(URL);
dbConn= ds.getConnection(userID, userPASS);
commStmt = dbConn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
dbResults= commStmt.executeQuery(sqlQuery);
}
catch (SQLException e)
{
System.out.println(e.toString());
}
}
We are getting an null pointer exception at the while loop within the try statement. The SQL does not have any errors. Any help would be appreciated

Looks like the dbResults field is static on the Driver class - this could cause serious problems with multi-threading, and does not utilize proper object-orientation - but that's beyond the scope of the question i guess.
Looking at the loop:
int employeeID= dbResults.getInt(1);
This is fine-ish, even though getInt() won't throw an NPE, you might want to check if the value was SQL null with ResultSet.wasNull().
String employeeFName = dbResults.getString(2);
String employeeLName = dbResults.getString(3);
These can be null, but won't throw NPE either.
System.out.println("Employee " +employeeID + employeeFName + employeeLName);
txtaOutput.appendText("Employee" +employeeID + employeeFName + employeeLName);
Here, in both lines, you concat strings that could be null, so these two are potential sources of NullPointerExceptions. I am just wondering if you got line numbers in your stacktrace that could help identifying the exact location...?
If you want to check what can/cannot return null from an SQL ResultSet, check this.

Related

NumberFormatException Spring

Below code...
#GetMapping("/brian/{number}")
public String getBrianMessage(#PathVariable int number) throws NumberFormatException {
try {
logList.add(number);
String stringList = logList.toString();
return "List is " + stringList;
} catch (NumberFormatException e){
int newCount= 999;
logList.add(newCount);
String stringList = logList.toString();
return "List is " + stringList;
}
}
When going to the url i would like the integer stored in a list. This works fine when you use a valid integer value. I want the ability to default the value to 999 when a string is supplied. So, if i go to /brian/string it should add 999 to the list and return it. This is not working and I'm getting the same error as before I added the exception handling

Adding a class to an ArrayList, but got NullPointerException [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
So, I was trying to add a class to an ArrayList, but when I do it gives me a Null Pointer Exception. I'm sure I am just overlooking a variable that I thought was initialized, but I can't figure it out.
This is the class:
enum WebType { GoogleResult, Webpage };
public class Webpage {
WebType type;
String pageName;
String content;
String url;
String MLA = "";
public Webpage(String pageName, String content, String url, WebType type){
this.type = type;
this.pageName = pageName;
this.content = content;
this.url = url;
this.MLA = ""; // Temp
}
// TODO: Make Citation Maker
}
This is where I add the class to the ArrayList:
public void Start(){
for(Integer i = 0; i < tags.size(); i++){
if(tags.get(i) == null)
return;
Webpage page = Google(tags.get(i));
parseList.add(page); // The Error is on this line!
log.append("Added " + page.url + " to parse list");
}
for(Integer i = 0; i < parseList.size(); i++){
ParsePageCode(parseList.get(i));
}
}
Here is the Google function, it googles whatever you tell it to and returns the page information:
public Webpage Google(String search){
String url = "https://www.google.com/search?q=" + search;
String content = "";
try {
URLEncoder.encode(url, "UTF-8");
} catch (UnsupportedEncodingException e) {
log.append("\n Unsupported Encoding Contacting Google");
}
try {
content = GetPageCode(url);
} catch (IOException e) {
log.append("\n Unable To Reach Google");
log.append(e.getMessage());
}
Webpage w = new Webpage("Google Result For " + search, content, url, WebType.GoogleResult);
// System.out.println(search + url + WebType.GoogleResult);
return w;
}
Any Ideas?
On the line that is throwing the exception, parseList is the only variable being dereferenced. The only other variable on that line is page, and it doesn't matter if page is null because you can add null elements to a List. So, it must be parseList causing the NPE.
Actually there is no problem adding null to a collection of Objects. Retrieving the object and invoking its members later may cause NPE.
You have told is that the problem is on the line where you do add the object. The only way there to cause NPE is calling add() upon null. So that's your collection parseList that is not initialized yet. Maybe it's a field in the class and was never initialized to an actual object of type ArrayList, but it's only declared.

How to fix error using equalsIgnorecase in java netbeans?

I am building java project in inventory management. following is the code i used for inserting color in database using equalsIgnorecase but it continuous showing Already exist. Please some one fix my code.
thanks
private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {
if(txtNewColor.getText().equals(""))
{
JOptionPane.showMessageDialog(null, "Fields should not be empty");
}
else
{
try {
String c = txtNewColor.getText();
ps =DbConnection.cn.prepareStatement("Select Color from color_details");
rs = ps.executeQuery();
int color = 0;
while (rs.next())
{
String cl= rs.getString("Color");
if(cl.equalsIgnoreCase(cl));
{
JOptionPane.showMessageDialog(null, "Aready Exist");
txtNewColor.setText("");
color=1;
}
}
if (color==0)
{
String strdata="Insert into color_details (Color)values(?)";
ps=DbConnection.cn.prepareStatement(strdata);
ps.setString(1, txtNewColor.getText());
ps.execute();
JOptionPane.showMessageDialog(null, "New Color Added Successfully");
cleartext();
}
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null, e);
}
}
refreshTable();
}
Try change if(cl.equalsIgnoreCase(cl)); to if(c.equalsIgnoreCase(cl))
Had not spotted the semi-colon at the end of your if statement
You are comparing the same String again. So It always results in a true, also the ; will skip even if they match. Remove it.
String c = txtNewColor.getText();
ps =DbConnection.cn.prepareStatement("Select Color from color_details");
rs = ps.executeQuery();
int color = 0;
while (rs.next())
{
String cl= rs.getString("Color");
if(cl.equalsIgnoreCase(c))
{
JOptionPane.showMessageDialog(null, "Aready Exist");
txtNewColor.setText("");
color=1;
}
}
You used same two strings to compare. so change c.equalsIgnoreCase(c1). Also make sure you have removed trailing spaces when getting input from text fields. it may makes your comparison fail.
String c = txtNewColor.getText().trim();
Remove the semi colon after if clause
if(cl.equalsIgnoreCase(cl)); ---> if(cl.equalsIgnoreCase(cl))

Mysql: Get Strings?

I try to receive all names out of my database.
I did write this code:
public static String getCmdCommand(int resultCount) throws Exception {
try {
// This will load the MySQL driver, each DB has its own driver
Class.forName("com.mysql.jdbc.Driver");
// Setup the connection with the DB
connect = DriverManager.getConnection(""+MyBot.mysqlDbPath+"",""+MyBot.mysqlDbUsername+"",""+MyBot.mysqlDbPassword+"");
PreparedStatement zpst=null;
ResultSet zrs=null;
zpst=connect.prepareStatement("SELECT `befehlsname` FROM `eigenebenutzerbefehle`");
zrs=zpst.executeQuery();
if(zrs.next()){
return zrs.getString(resultCount);
}else{
return "-none-";
}
}catch (Exception e) {
throw e;
} finally {
close();
}
}
and i start the method by running a loop:
for(int i = 0; i <= cmdAmount-1; i++){
try {
eebBenutzerBefehl = dao.getCmdCommand(i);
} catch (Exception e) {
e.printStackTrace();
}
}
cmdAmount is a integer with the valuable of the total fields inside the database.
so i.e My database holds name1 name2 name3, is it wrong to call them like this? :
return zrs.getString(resultCount);
which should be:
zrs.getString(0) = name1
zrs.getString(1) = name2
zrs.getString(2) = name3
I always receive java.sql.SQLException: Column Index out of range, perhaps it just continue to check the first entry only in the database :confused:
return zrs.getString(resultCount);
The getString() method should be given the index of the column you want to return which is always going to be the same. You should pass in a constant here such as 0.
Also, you should open the database only once rather than over and over again in that one method by passing in the "connect" variable as a parameter.
Here's what I would do if you are wanting to retrieve the name from each row of the table.
public static ArrayList<String> getCmdCommand(Connection connect) throws Exception {
try {
PreparedStatement zpst=null;
ResultSet zrs=null;
ArrayList<String> names = new ArrayList<String>();
zpst=connect.prepareStatement("SELECT `befehlsname` FROM `eigenebenutzerbefehle`");
zrs=zpst.executeQuery();
// The result set contains all the names retrieved from the call to the database, so
// you just need to iterate through them all and store them in a list.
while(zrs.next()) {
names.add(zrs.getString(0));
}
} catch (Exception e) {
throw e;
} finally {
close();
}
return names;
}
You don't need to tell it how many fields there are because it will figure that out itself.
Class.forName("com.mysql.jdbc.Driver");
Connection connect = DriverManager.getConnection(""+MyBot.mysqlDbPath+"",""+MyBot.mysqlDbUsername+"",""+MyBot.mysqlDbPassword+"");
try {
ArrayList<String> names = dao.getCmdCommand(connect);
} catch (Exception e) {
e.printStackTrace();
}
if(names.size() < 1) {
// " - none - "
}

Null Pointer Exception: null error [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I have this Hash Set code and when I try to run my compile method on it I get the Null Pointer Exception: null error on it. Here is the code:
private void initKeywords() {
keywords = new HashSet<String>();
keywords.add("final");
keywords.add("int");
keywords.add("while");
keywords.add("if");
keywords.add("else");
keywords.add("print");
}
private boolean isIdent(String t) {
if (keywords.contains(t)) { ***//This is the line I get the Error***
return false;
}
else if (t != null && t.length() > 0 && Character.isLetter(t.charAt(0))) {
return true;
}
else {
return false;
}
}
The other lines that goes along with this error is:
public void compileProgram() {
System.out.println("compiling " + filename);
while (theToken != null) {
if (equals(theToken, "int") || equals(theToken, "final")) {
compileDeclaration(true);
} else {
compileFunction(); //This line is giving an error with the above error
}
}
cs.emit(Machine.HALT);
isCompiled = true;
}
private void compileFunction() {
String fname = theToken;
int entryPoint = cs.getPos();
if (equals(fname, "main")) {
cs.setEntry(entryPoint);
}
if (isIdent(theToken)) theToken = t.token(); ***//This line is giving an error***
else t.error("expecting identifier, got " + theToken);
symTable.allocProc(fname,entryPoint);
accept("(");
compileParamList();
accept(")");
compileCompound(true);
if (equals(fname, "main")) cs.emit(Machine.HALT);
else cs.emit(Machine.RET);
}
Are you sure you're running initKeywords() before isIdent()?
Either keywords or t is null. Using either a debugger or print statements it should be pretty simple to determine. If keywords is null, I'd assume that initKeywords() has not been called yet.
You probably want to call initKeywords from the constructor of this object.
I personally try to stay away from init methods. As previously mentioned, a constructor serves as an initializer, and so does the static block:
private final static Set<String> KEYWORDS = new HashSet<String>();
static {
keywords.add("final");
keywords.add("int");
keywords.add("while");
keywords.add("if");
keywords.add("else");
keywords.add("print");
}

Categories