/ java.lang.NullPointerException: How to resolve ~ Java EE Support Patterns

1.22.2012

java.lang.NullPointerException: How to resolve

Exception in thread "main" java.lang.NullPointerException is one of the common problems and Java error that you will face when developing pure Java or Java EE applications. This Java Exception has been around since early JDK days e.g. JDK 1.0.

Most of you probably have seen and resolve this problem many times so this article is mainly dedicated for individuals new in Java or interested to revisit this Java Exception.

java.lang.NullPointerException: Overview

NullPointerException is a runtime Exception thrown by the JVM when your application code, other referenced API(s) or middleware (Weblogic, WAS, JBoss...) encounters the following conditions:

-        Attempting to invoke an instance method of a null object
-        Attempting to access or modify a particular field of a null object
-        Attempting to obtain the length of such null object as an array

java.lang.NullPointerException: Sample Java program

** Tutorial video is now available: http://www.youtube.com/watch?v=5_jTMXOcteo

It is always best to learn with examples and sample Java programs. The program below is a very simple Java program generating a java.lang.NullPointerException. Please simply copy/paste and run the program with the IDE of your choice (Eclipse IDE was used for this example).

package org.ph.java.courses;

/**
 * NullPointerExceptionSampleProgram
 * @author Pierre-Hugues Charbonneau
 *
 */
public class NullPointerExceptionSampleProgram {
      
       private String field1 = null;
       private String field2 = null;   
      
       public String getField1() {
             return field1;
       }

       public void setField1(String field1) {
             this.field1 = field1;
       }

       public String getField2() {
             return field2;
       }

       public void setField2(String field2) {
             this.field2 = field2;
       }

       /**
        * @param args
        */
       public static void main(String[] args) {
            
             try {
                    // Create a fresh object instance
                    NullPointerExceptionSampleProgram objectInstance =
                                 new NullPointerExceptionSampleProgram();                   
                    // Initialize field1...
                    objectInstance.setField1("field1Value");
                   
                    // reset our object instance to null
                    objectInstance = null;
                   
                    // Now initialize field2...BOOM! >> NullPointerException!
                    objectInstance.setField2("field1Value2");
            
             } catch (Throwable any) {
                    System.out.println("Java ERROR: "+any);
                    any.printStackTrace();
             }
            
       }

}

If you run the program as is, you will see the output as per below:

java.lang.NullPointerException
       at org.ph.java.courses.NullPointerExceptionSampleProgram.main
(NullPointerExceptionSampleProgram.java:47)

Java ERROR: java.lang.NullPointerException

As you can see in our example, the NullPointerException is thrown when attempting to execute the setField2() method against our objectInstance which is now null.

The JVM will typically show you the line of code (line 47 in this example) where the NullPointerException is triggered. This is critical data since it allows you to trace back the problem in your application Java code at this particular line of code of the affected Java class.

java.lang.NullPointerException: Resolution strategies

Now that you understand this problem, it is now time to resolve it. Complexity of the resolution will depend of the context of your problem since NullPointerException can be a problem by itself or simply a symptom of another problem (no data returned from a Web Service call etc.). Regardless of the context & root cause, you must shield your Java code and add proper error handling and null check validations when applicable:

-        Review the java.lang.NullPointerException Stack Trace and determine where the Exception is triggered (your application code, third part API, middleware software such as Weblogic etc.) and extract the line #
-        If problem is at your application code then a code walkthrough will be required. If problem is found from third party API and / or middleware, my recommendation is to first review your referenced code and determine if it could be indirectly be the source of the problem e.g. passing a null value to a third part API method etc.
-        If problem found within your application code, then attempt to determine which Object instance is null and causing the problem. You will need to modify your code in order to add proper null check validations and proper logging so you can understand the source of the null value as well

Now back at our example, a simple validation and logging can be added as per below:

** Please note that logging should be done via standard logging framework such as Log4J **

// Now Initialize field2 but only if objectInstance is not null
if (objectInstance != null) {
objectInstance.setField2("field1Value2");
} else{
       System.out.println("objectInstance is null, do not attempt to initialize field2");
}

Conclusion and best practices

Best practices include:

-        Add proper null check validations before attempting to use an object Instance method e.g. if (objectInstance != null) { objectInstance.method(); }
-        When a null object is found, please add proper logging so you can pinpoint the root cause / source of the null value
-        Avoid too many object instance method calls on a single line as it will increase diagnostic complexity in the event of a NullPointerException e.g. avoid calls like this below unless properly checked for null prior to the call:
objectInstance.method(objectInstance2.getData(), objectInstance3.getData(),objectInstance4.getData());

I hope this article has helped you to understand and revisit this Java Exception.
Please feel free to add any comment or question if you are still struggling with a java.lang.NullPointerException problem.

55 comments:

Hi P-H, thanks for another good post. Just like NoClassDefFoundError is biggest nightmare of experienced programmer, NPE is biggest nemesis for beginners, its way more frustrating until you get hold of it. I have shared some common cause of NullPointerException in Java, which seems to be good compliment to this post and help people to get around of NPE.

Hi P-H...., ur article really helped me alot.

thanks alot

Many Thanks. I've been tearing my hair out for days!
Hopefully will now be able to pinpoint the problem.

Thanks for your comments.

Please feel free to share your problem case if you are still struggling.

P-H

Plz am still having issues.... when i click the login button of my login form it gives me that error....Plz dis is a segment of my code..kindly check it out

Connection con ;
ResultSet rs;
PreparedStatement pst;

public Login_jframe() throws ClassNotFoundException {
initComponents();
javaconnect.getConnection();

}



private void cmd_LoginActionPerformed(java.awt.event.ActionEvent evt) {
String sql="select * from secrets where Username=?, and Password=?";
try{
pst=con.prepareStatement(sql) ;
pst.setString(1, txt_Username.getText());
pst.setString(2, txt_Password.getText());

rs=pst.executeQuery(sql);
int tmp=0;

if(rs.next()){

JOptionPane.showMessageDialog(null, "Username and Password is correct");
Home s=new Home();
s.setVisible(true);
}
else {
JOptionPane.showMessageDialog(null, "Username and Password is not correct");
Entry z=new Entry();
z.setVisible(true);
}

}
catch(Exception ex){
JOptionPane.showMessageDialog(null, ex);

}
// TODO add your handling code here:
}

/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/*
* Set the Nimbus look and feel
*/
//
/*
* If Nimbus (introduced in Java SE 6) is not available, stay with the
* default look and feel. For details see
* http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Login_jframe.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Login_jframe.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Login_jframe.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Login_jframe.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//

/*
* Create and display the form
*/
java.awt.EventQueue.invokeLater(new Runnable() {

public void run() {
try {
new Login_jframe().setVisible(true);
} catch (ClassNotFoundException ex) {
Logger.getLogger(Login_jframe.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}

Hi Anonymous,

I will review the code but can you please also provide the StackTrace of the NullPointerException that you are getting e.g. we need to understand which line of code is triggering this error.

Thanks.
P-H

I'm trying to fill out an application for a school in Korea. When I try to save the page I get the java.lang.NullPointerException message being discussed on this page. I tried both Firefox and Safari. Same message. I'm not programmer and the conversation here is beyond me. My only question is, is this something that can be fixed on my end or is this a problem originating on the application end? Thank you, Maria

Hi Mario,

If you are seing a java.lang.NullPointerException from your browser after filling a form then problem is very likely on the hosting Java application.

Please contact the support team of this school in Korea so they can investigate their server logs.

Thanks.
P-H

I found following error when i am trying to open properties of ARETU of Node-B (Ericssson 3G BTS)
Exception: RuntimeException
java.lang.NullPointerException
ava.lang.RuntimeException: java.lang.NullPointerException
at se.ericsson.cello.support.gui.guilib.infra.ApplicationManager.runApplication(Unknown Source)
at se.ericsson.cello.support.gui.LaunchExternalApplication.run(Unknown Source)
Caused by: java.lang.NullPointerException
at se.ericsson.security.launcher.cache.Cache.getFileFromURL(Unknown Source)
at se.ericsson.security.launcher.cache.Cache.getFile(Unknown Source)
at se.ericsson.security.launcher.cache.Cache.prepareApplication(Unknown Source)
at se.ericsson.security.launcher.Launcher.runApplication(Unknown Source)
... 2 more

public newInsert() {
initComponents();
dbconnect();
}

public void dbconnect()
{
String url = "jdbc:mysql://localhost:3306/";
String dbName = "users";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "";
try {
Class.forName(driver).newInstance();
con = DriverManager.getConnection(url+dbName,userName,password);

//stmt = con.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE );
stmt = con.createStatement();
}
catch(Exception e){

}
}

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {

String s1 = TextName.getText();
String s2 = PasswordField.getText();
String s3 = TextEmail.getText();


try{
stmt.close();
//Statement stmt = this.con.createStatement();
// stmt.executeUpdate("insert into registration (Name , Password , Email ) values ('" + s1+ "','"+s2+ "','"+s3 + "')");
stmt=con.createStatement();
String sql=("Insert into registration (Name , Password , Email) values('"+(s1)+"','"+(s2)+"','"+(s3)+"')");
stmt.executeUpdate(sql);

}catch(Exception e){

System.out.println(e.toString());

}
}



this is my code but it gives me java.lang.NullPointerException exception. what can i do? my database field is ID,Name,Password,Email

plz help me..

Hi Anonymous,

Do you have the NullPointerException stack trace so we can see at which line of code your are getting your NPE?

The above code appears to be non managing properly the creation and close of the Statement object but first let's review your full stack trace and line of code where NPE is triggered.

Thanks.
P-H

private void C_UN_ButtonActionPerformed(java.awt.event.ActionEvent evt) {

try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:HMS_DS","","");
String C_pw1=Cr_C_UN_PW_TextField.getText();

String ap1="";
String ap2="";
String C_un1 = Cr_C_UN_UN_TextField.getText();
String N_un1 = N_UN_TextField.getText();
String Con_un1 = Con_UN_TextField.getText();


rs=stmt.executeQuery("select * from Admin_Login where A_PW ='"+C_pw1+"'");

while(rs.next())
{
ap1=rs.getString(1);

if(C_un1.equals(ap1))
{
if(N_un1.equals(Con_un1))
{
ps=con.prepareStatement("Update Admin_Login SET A_UN = ? where A_PW ='"+C_pw1+"'");

ps.setString(1,Con_un1);
ps.setString(2, C_pw1);
ps.executeUpdate();
JOptionPane.showMessageDialog(null,"UsrName Changed");
Cr_C_PW_UN_TextField.setText("");
N_UN_TextField.setText("");
Con_UN_TextField.setText("");
}

}
else
{
JOptionPane.showMessageDialog(null,"Please check your Password n type Again");


}
}
}
catch(Exception Ex)
{
JOptionPane.showMessageDialog(null, Ex);
}
}




sir this is the codes and i want to change username from database but it through java.lang.NullpointerException help me sir

I have been unable to connect with the 4shared site for over a week. I get the following error message. I have read the above info but don't know how to run the fix noted in the top box. I would appreciate your help


HTTP Status 500 -

--------------------------------------------------------------------------------

type Exception report

message

description The server encountered an internal error () that prevented it from fulfilling this request.

exception

java.lang.NullPointerException


note The full stack trace of the root cause is available in the Apache Tomcat/6.0.16 logs.


--------------------------------------------------------------------------------

Apache Tomcat/6.0.16

Hi anonymous,

I assume you get the error when you attempt to connect through the 4shared Internet site e.g. file sharing provider. Is that correct?

Thanks.
P-H

Thanks so much for your response!

Yes -- I have a free account there for downloading files. I cannot get to the download page that comes just before the sign in page.

I can get to it on my netbook but not my primary computer.

Hi anonymous,

The error you get is server side from the 4shared site. This is not something you can fix on your side (client). I recommend 2 actions at this point:

1) Clear your cache etc, or try with more browser types & versions from your primary computer
2) Contact 4shared technical support and provide them the error. They may be able to look at their Apache Tomcat server logs and see what is the problem with your account

Regards,
P-H

Many thanks for this information & suggestions.
I have cleared the cache several times & have installed Firefox & I can get to the sign in page but it stalls & doesn't move forward.
I will contact their support & hopefully get the issue resolved.

I appreciate your help very much!
Thanks again

Sorry but this is way over my head, all I know is that when I am trying to down load from Google Cloud on to My Samsung Tablet I get java.lang.NullPointerException.

The system worked up until yesterday any clear basic help you can give would be appreciated

Hi Anonymous,

Do you have a snapshot of the java.lang.NullPointerException from your Samsung tablet that you can share? Do you see a list of stack trace lines or just this one liner java.lang.NullPointerException?

Thanks.
P-H

Hi sir, while trying to run the below code in tomcat server, caught with the Null Pointer exception while clicking "submit button" in the form.

Code:
<%@ page import="java.sql.*" %>

<%@ page import="java.io.*" %>


<%

String name = request.getParameter("name");
String city = request.getParameter("city");

String phone = request.getParameter("phone");

String connectionURL ="jdbc:mysql://localhost:3306/studentdb";

Connection connection = null;

PreparedStatement pstatement = null;

Class.forName("com.mysql.jdbc.Driver").newInstance();

int updateQuery=0;

if(name!=null && city!=null && phone!=null){

if(name!="" && city!="" && phone!="") {

try {

connection = DriverManager.getConnection(connectionURL,"root","root");

String queryString = "INSERT INTO stu_info(Name,City,Phone) VALUES (?,

?, ?)";

pstatement = connection.prepareStatement(queryString);

pstatement.setString(1, name);

pstatement.setString(2, city);

pstatement.setString(3, phone);

updateQuery = pstatement.executeUpdate();

if (updateQuery != 0) { %>



out.println("Data is inserted successfully in database.")



<%

}

}

catch (Exception ex) {

out.println("Unable to connect to batabase.");

}

finally {

pstatement.close();

connection.close();

}

}

}

%>


Exception:
exception

org.apache.jasper.JasperException: An exception occurred processing JSP page /databaseinsertion.jsp at line 117

114:
115: finally {
116:
117: pstatement.close();
118:
119: connection.close();
120:


Stacktrace:
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:521)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:430)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
root cause

java.lang.NullPointerException
org.apache.jsp.databaseinsertion_jsp._jspService(databaseinsertion_jsp.java:172)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:388)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)


Sir,
can u please resolve it,

Hi Rekha,

The NPE you are getting is because your pstatement object is null, causing failure when you are attempting to close it.

Please add logging and understand why your pstatement is null, you are likely getting an Exceptin when executing this line:
pstatement = connection.prepareStatement(queryString);

Best practices also include to validate JDBC related objects for null before attempting to close e.g. replace your code closure by this:

finally {

if (pstatement != null)pstatement.close();
if (connection != null)connection.close();

}

I used a scanner method to scan in a string and the toCharArray method but it gives me this error:
java.lang.NullPointerException
at SuperAnagram.(SuperAnagram.java:4)
at SuperAnTester.main(SuperAnTester.java:10)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)

Hi Jake,

Can you please share the Java code from the class: SuperAnagram.java
We need to look at line #4 in order to see which variable or object is null.

Thanks.
P-H

Hi P-H,

I am using Oracle SQL Developer to pull out tables for my client. It gives me Failure-java.lang.NullPointerException. I am not a programmer and dont understand Java. Please help me out.

Thanks,
Aditya

Hi Aditya,

Can you please share the entire Exception stack trace. You will likely see this from the SQL Developer logs.

Thanks.
P-H

Hi Pierre,

This is what it says.

java.lang.NullPointerException
at oracle.dbtools.raptor.conntypes.RaptorClassLoader.findClassLoader(RaptorClassLoader.java:48)
at oracle.dbtools.raptor.conntypes.RaptorConnectionWrapper.createConnectionImpl(RaptorConnectionWrapper.java:202)
at oracle.dbtools.raptor.conntypes.RaptorConnectionWrapper.createConnection(RaptorConnectionWrapper.java:160)
at oracle.dbtools.raptor.conntypes.RaptorConnectionWrapper.getJdbcConnection(RaptorConnectionWrapper.java:191)
at oracle.dbtools.raptor.conntypes.RaptorConnectionWrapper.getPresentation(RaptorConnectionWrapper.java:66)
at oracle.dbtools.raptor.utils.Connections$ConnectionInfo.createConnection(Connections.java:781)
at oracle.dbtools.raptor.utils.Connections$ConnectionInfo$ConnectRunnable.doWork(Connections.java:654)
at oracle.ide.dialogs.ProgressRunnable.run(ProgressRunnable.java:159)
at oracle.ide.dialogs.ProgressBar.run(ProgressBar.java:553)
at java.lang.Thread.run(Thread.java:595)

Thanks,
Aditya

Hi I recommend that you review this Oracle forum thread as it describes the same problem with possible solutions. You may also want to explore to install the latest version of SQL Developer.

https://kr.forums.oracle.com/forums/thread.jspa?threadID=863466

Thanks.
P-H

Hi Pierre,

Thanks for the help, I realized the problem was because of improper installation of Java.

Thanks,
Aditya

Thanks Scythe for posting back the solution to your problem.

Happy to help.

Regards,
P-H

hi,
i m looking for .mdl to .ecore conversion.
will u help me out with brief steps.

help plzz...
its an isc board exam question
juz practising
done in bluej


import java.io.*;
public class pseudoarithmetic
{
int n,a[],ans,flag,sum,r,flag1,flag2;
void pseudoarithmetic()throws IOException
{
n=ans=flag=flag1=flag2=sum=r=0;
}
void accept(int nn)throws IOException
{
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
n=nn;
int a[]=new int[n];
System.out.println("Enter the elements of the array.");
for(int i=0;i<n;i++)
{
a[i]=Integer.parseInt(br.readLine());
}
for(int i=0;i<a.length;i++)
{
System.out.print(a[i]+" ");
}
}
boolean check()throws IOException
{
r=a[0]+a[n-1];
if((n%2)==0)
{
flag1=0;
for(int i=0;i<n/2;i++)
{
sum=a[i]+a[n-1-i];
if(sum==r)
flag=1;
else
{
flag=0;
break;
}
}
}
else
{
for(int i=0;i<(n-1)/2;i++)
{
sum=a[i]+a[n-1-i];
ans=a[(n-1)/2];
if(sum==r && r==ans)
flag=1;
else
{
flag=0;
break;
}
}
if(flag==1)
{
flag2=1;

if(flag1==1)
{
sum=sum*(n/2);
}
else
{
sum=sum*((n+1)/2);
}
System.out.println("Sum = "+sum);

}

}
if(flag2==1)
return true;
else
return false;
}
public static void main(String[] args)throws IOException
{
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
pseudoarithmetic obj=new pseudoarithmetic();
obj.pseudoarithmetic();
obj.accept(6);
boolean x=obj.check();
if(x==true)
System.out.println("the entered sequence is pseudoarithmetic.");
else
System.out.println("the entered sequence is not pseudoarithmetic.");
}
}

hey can you help me with a NULLPOINTER exception problem

Hi Sakthi,

Please post the full NullPointerException error and stacktrace that you are getting and let me know under which context you are getting this e.g. Java programming or using software/game?

Thanks.
P-H

type Exception report

message java.lang.NullPointerException

description The server encountered an internal error that prevented it from fulfilling this request.

exception

org.apache.jasper.JasperException: java.lang.NullPointerException
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:502)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:430)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)


root cause

java.lang.NullPointerException
org.apache.jsp.index2_jsp._jspService(index2_jsp.java:75)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:388)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)


note The full stack trace of the root cause is available in the Apache Tomcat/6.0.36 logs.


--------------------------------------------------------------------------------

Apache Tomcat/6.0.36

Hi, I would appreciate if you could help me out. So basically the following code is used to create an AVL Tree in Java. Our lecturer wants us to create our tree from scratch, including the methods.

The problem I get is when it comes to Inserting a new Node, the root value is not being set and when I remove the snippet of code that prints error, a Null Pointer Exception is thrown.

I would appreciate if anyone could shed some light on my problem and explain what I'm doing wrong.

Thank you very much for your time

IDE used: Netbeans

AVLTree tree = new AVLTree();
for(int i = 0; i < ints.length; i++)
{
Node node = new Node(ints[i]);
tree.Insert(node,tree);
System.out.println("PASS " + (i+1) + ":");
System.out.println("LEFT NODE:\tDATA:\tRIGHT NODE:");
for(int j = 0; j <= i; j++)
{
System.out.println(" \t"+ints[j]+"\t");
}
System.out.println(tree.getRoot().getData());
//System.out.println(tree.getRoot().getLeftNode().getData());
//System.out.println(tree.getRoot().getRightNode().getData());
}

}

Part 2: Please find the Insert code snippet

public void Insert(Node node,AVLTree tree)
{
if((tree.getRoot()) == null)
{
AVLTree t = new AVLTree();
if(tree.getRoot() == null)
{
System.out.println("Error");
}
else
{
tree.setRoot(node);
tree.getRoot().setData(node.getData());
tree.setLeftTree(null);
tree.setRightTree(null);
tree.getRoot().setHeight(0);
}
}
else
{
if(node.getData() < tree.getRoot().getData())
{
Insert(node,tree.getLeftTree());
if((Height(tree.getLeftTree().getRoot()) - Height(tree.getRightTree().getRoot())) == 2)
{
if(node.getData() < tree.getLeftTree().getRoot().getData())
{
SingleRotateLeft(tree);
}
else
{
DoubleRotateRight(tree);
}
}
else
{
tree.getRoot().setHeight(1+Max(Height(tree.getLeftTree().getRoot()),Height(tree.getRightTree().getRoot())));
}
}
else if(node.getData() > tree.getRoot().getData())
{
Insert(node,tree.getRightTree());
if((Height(tree.getRightTree().getRoot()) - Height(tree.getLeftTree().getRoot())) == 2)
{
if(node.getData() < tree.getRightTree().getRoot().getData())
{
SingleRotateRight(tree);
}
else
{
DoubleRotateLeft(tree);
}
}
else
{
tree.getRoot().setHeight(1+Max(Height(tree.getLeftTree().getRoot()),Height(tree.getRightTree().getRoot())));
}
}
else if(node.getData() == tree.getRoot().getData())
{
System.out.print("Data already exists");
}
}
}

hello.
i have a problem.
how i want to call text field data from other form?
my situation is,
i want to make reservation button for reservation form. when user click reservation, their data will appear on the text fields.
the code for the button will refer to Username text field in the Login Form. How i want to call the data?

Hi,author
I've encounter the same problem..If I post to u my codes,how long will you take to pinpoint and correct my mistakes? I don't think my code is a difficult one, but I'm a complete beginner in java, so I'm having hard time finding which part did I done wrong..

import java.awt.*;
import java.awt.event.*;

public class Awt implements ActionListener{
public Frame f;
public Button b1,b2,b3;

public Label l1,l2,l3;

public TextField t1,t2,t3;

public void Awt(){
f=new Frame("Arithmetic");
b1=new Button("ADD");
b2=new Button("MULTIPLY");
b3=new Button("Subtraction");
t1=new TextField("\t \t");
t2=new TextField("\t \t");
t3=new TextField("\t \t");

}
public int frame(){
f.setLayout(new GridLayout(4,2));
f.add(l1);
f.add(t1);
f.add(l2);
f.add(t2);
f.add(b1);
f.add(b2);
f.add(l3);
f.add(t3);
b1.addActionListener(this);
b2.addActionListener(this);
return 1;
}
public static void main(String[] args) {
try
{
Awt a=new Awt();

a.frame();// TODO code application logic here
}
catch(Exception e)
{
System.out.print("error is "+e);
}
}



@Override
public void actionPerformed(ActionEvent e){
double d = Double.parseDouble(t1.getText());
double c = Double.parseDouble(t2.getText());

int b=(int) ((int) c+d);
t3.setText(Integer.toString(b));

}
}





GETTING NULLPOINTER EXCEPTION PLS HELP ME WITH IT

Hi jhawahar,

Can you please also provide the full Exception stack trace when you get the error and exact line of code where the NPE is triggered?

Thanks.
P-H

Hi Pierre,

Could you please help me to solve the problem below?:

java.lang.NullPointerException
at shared.Money.subtract(Money.java:91)
at shared.AuctionInfo.getCurrentBid(AuctionInfo.java:202)
at gui.veiling.createAuction(veiling.java:54)
at gui.veiling.(veiling.java:39)
at gui.veilinglijst.updateList(veilinglijst.java:294)
at source.Client.KickList(Client.java:157)
at source.Client$1.run(Client.java:189)

Hi Claude,

We can see that the NPE is triggered within the following code:

at shared.Money.subtract(Money.java:91) e.g. Java class: Money, at line 91.

Do you have access to the source code so you can identify what potential object is null?

Regards,
P-H

Hi Pierre,

Thanks for your reply. Yes I have access to the source code but the application is very complex. I cannot see where the object is null.
Do you have a TeamViewer so that I share my code with you?

Thanks again.

Claude

Hi Claude,

You can email me a snippet of your code (Money.java) at: phcharbonneau@hotmail.com

Hi Pierre-Hugues,

I just mail you the Money.java code as requested.

Regards,
Claude

I use bukkit server and it says it when every I open it java.null.pointerexception please help!

Sincerely, Anonymous

Hi anonymous,

Do you have the source code of the Java class throwing the java.lang.NullPointerException?

Thank you P-H.

The article was helpful to me.

Regards
Ahmed

Thanks alot your article really helped me out.
All the best man

Hi P-H. I am beginner in Java and Im learning from stanford exercises on youtube. One assingment is to make game called breakout, but I have problems when invoking method on ball to move. Here is what I get:

"java.lang.NullPointerException
at Breakout.movekugla(Breakout.java:244)
at Breakout.init(Breakout.java:77)
at sun.applet.AppletPanel.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)"

Here is the part of the code where it points to:

public void movekugla(){
vx = rgen.nextDouble(1.0, 3.0);
if (rgen.nextBoolean(0.5)) vx = -vx;
vy=+3.0;
kugla.move(vx,vy);

and also on method movekugla(); like this:
public void init() {
setSize(400,600);
addMouseListeners();
red();
red2();
red3();
red4();
red5();
red6();
red7();
red8();
red9();
red10();
paddle();
kugla();
movekugla();

And it says, Applet not initialized

P.S. kugla=ball (kugla means ball on my language)

Please help, kind regards

Hi Mr. P-H,

I got some trouble java.lang.NullPointerException when i want to save the data (core.save(data))~

@SuppressWarnings("serial")
public class CoreServiceController extends JFrame implements ActionListener,
FocusListener, MouseListener {

@Autowired CoreServiceService core;

...

public void actionPerformed(ActionEvent splatter) {
if (splatter.getSource() == cmdBrowse) {
browseCSV();
cmdReset.setEnabled(true);
cmdLoad.setEnabled(true);
}
if (splatter.getSource() == cmdLoad) {
try {
LoadData();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (splatter.getSource() == cmdReset) {
inisialisasi();
}
}

private void browseCSV() {
JFileChooser jfc = new JFileChooser();
FileFilter fileFilter = new FileFilter() {
@Override
public boolean accept(File f) {
if (f.getName().toLowerCase().endsWith(".csv")
|| f.isDirectory()) {
return true;
} else {
return false;
}
}
@Override
public String getDescription() {
return "*.csv";
}
};

jfc.addChoosableFileFilter(fileFilter);
jfc.setMultiSelectionEnabled(false);
jfc.showOpenDialog(this);
// mengambil path file
String path = jfc.getSelectedFile().getAbsolutePath();
txtPath.setText(path);
}

public void LoadData() throws Exception{
String csvFile = validatePath(txtPath.getText().toString());
BufferedReader br = null;
String line = "";
String csvSplitBy = ";";
// int count_sys;
// int count_ser;

try {

br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null){

//pake ";" sebagai delimiter
String [] cs = line.split(csvSplitBy);
String module = cs[0].replaceAll("\\W", "");
//String module = cs[0].substring(1);
String system_id = cs[1];
String object = cs[2];
String tgl1 = cs[3];
String tgl2 = cs[4].substring(0, cs[4].length() - 1);

SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
Date log_date = sdf1.parse(tgl1);

SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:SS");
Date update_log = sdf2.parse(tgl2);

CoreService data = new CoreService();
data.setMODULE_NAME(module);
data.setSYSTEM_ID(system_id);
data.setOBJECT_NAME(object);
data.setLOG_DATE(log_date);
data.setUPDATE_LOG(update_log);
data.setCATEGORY("SYSTEMID");
data.setCOUNTER_SERVICE(1);
data.setCOUNTER_SYSTEM(1);

System.out.println(data);

//core.save(data);
System.out.println(module);
System.out.println(module+" ~ "+system_id+" ~ "+object+" ~ "+log_date+" ~ "+update_log);
}

} catch (FileNotFoundException e) {
// TODO: handle exception
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
} finally {
if (br != null){
try{
br.close();
}catch (IOException e){
e.printStackTrace();
}
}
}

System.out.println("sukses");

}

private String validatePath(String invalidPath) {
String validPath;
validPath = invalidPath.replace('\\', '/');
return validPath;
}

/**
* @param args
*/
public static void main(String[] args) {
new CoreServiceController();
}

....
}

thanks in advance :)

Hi, i'm also having some problems with Java.Lang.Nullpointerexception as well. I'm trying to log into NKO to do some work on my ASUS Transformer tablet but the page that keeps coming up is this

type Exception report

message java.lang.NullPointerException

description The server encountered an internal error that prevented it from fulfilling this request.

exception

org.apache.jasper.JasperException: java.lang.NullPointerException
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:502)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:430)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
javax.servlet.http.HttpServlet.service(HttpServlet.java:723)
root cause

java.lang.NullPointerException
org.apache.jsp.index2_jsp._jspService(index2_jsp.java:75)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:723)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:388)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
javax.servlet.http.HttpServlet.service(HttpServlet.java:723)
note The full stack trace of the root cause is available in the Apache Tomcat/6.0.37 logs.
Please if you can help me that would be wonderful, I really don't want to have to return my computer and cac card due to this code that is seeminly fixable.

Hi,
I am trying to access a jsp page by redirecting form the servlet. i am using weblogic server.
I am newbie to weblogic.
I am getting the Internal server error .
Below is the error it displayed.




Error 500--Internal Server Error
java.lang.NullPointerException
at jsp_servlet.__eprofileupdate._jspService(__eprofileupdate.java:205)
at weblogic.servlet.jsp.JspBase.service(JspBase.java:34)
at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:227)
at weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:125)
at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:301)
at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:184)
at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.wrapRun(WebAppServletContext.java:3732)
at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:3696)
at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:120)
at weblogic.servlet.internal.WebAppServletContext.securedExecute(WebAppServletContext.java:2273)
at weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:2179)
at weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1490)
at weblogic.work.SelfTuningWorkManagerImpl$WorkAdapterImpl.run(SelfTuningWorkManagerImpl.java:545)
at weblogic.work.ExecuteThread.execute(ExecuteThread.java:256)
at weblogic.work.ExecuteThread.run(ExecuteThread.java:221)



Please help me out in resolving this .

Thanks in advance.

Hi can anyone please help me i am passing data between the activities but it canot moving myy code is:
next.setOnClickListener(new OnClickListener() {

this is parent activty:
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub

String user=user_spinner.getSelectedItem().toString();
String group=group_spnner.getSelectedItem().toString();

Bundle b=new Bundle();


// if(user_spinner.getSelectedItem().toString().isEmpty()|| group_spnner.getSelectedItem().toString().isEmpty()){
//
// Toast.makeText(getApplicationContext(), "Please select data from Spinner",Toast.LENGTH_SHORT ).show();
//
// }
//
// else{


b.putString("user", user);
b.putString("group", group);

Intent net= new Intent(getApplicationContext(),Biodata.class);
net.putExtras(b);

startActivity(net);
// }
}

});



Second activity:


Bundle b=getIntent().getExtras();
user=b.getString("user");
group=b.getString("group");

showing the error in logcat is :in the first activity on the

String user=user_spinner.getSelectedItem().toString();
String group=group_spnner.getSelectedItem().toString();

Post a Comment