cancel
Showing results for 
Search instead for 
Did you mean: 

java.lang.NullPointerException

Former Member
0 Kudos

Hi Gurus,

I am working on an application where i need to display data from the portal database, on the basis of inputs given by the user; while doing so I am getting Null Pointer Exception. below is my code.

// ---------------------------------------------------------------------------

// This file has been generated partially by the Web Dynpro Code Generator.

// MODIFY CODE ONLY IN SECTIONS ENCLOSED BY @@begin AND @@end.

// ALL OTHER CHANGES WILL BE LOST IF THE FILE IS REGENERATED.

// ---------------------------------------------------------------------------

package com.lanco;

//

// IMPORTANT NOTE:

// _ALL_ IMPORT STATEMENTS MUST BE PLACED IN THE FOLLOWING SECTION ENCLOSED

// BY @@begin imports AND @@end. FURTHERMORE, THIS SECTION MUST ALWAYS CONTAIN

// AT LEAST ONE IMPORT STATEMENT (E.G. THAT FOR IPrivateZhse_displayView).

// OTHERWISE, USING THE ECLIPSE FUNCTION "Organize Imports" FOLLOWED BY

// A WEB DYNPRO CODE GENERATION (E.G. PROJECT BUILD) WILL RESULT IN THE LOSS

// OF IMPORT STATEMENTS.

//

//@@begin imports

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.Statement;

import com.lanco.wdp.IPrivateZhse_displayView;

import com.sap.tc.webdynpro.progmodel.api.WDVisibility;

//@@end

//@@begin documentation

//@@end

public class Zhse_displayView

{

  /**

   * Logging location.

   */

  private static final com.sap.tc.logging.Location logger =

    com.sap.tc.logging.Location.getLocation(Zhse_displayView.class);

  static

  {

    //@@begin id

    String id = "$Id$";

    //@@end

    com.sap.tc.logging.Location.getLocation("ID.com.sap.tc.webdynpro").infoT(id);

  }

  /**

   * Private access to the generated Web Dynpro counterpart

   * for this controller class.  </p>

   *

   * Use <code>wdThis</code> to gain typed access to the context,

   * to trigger navigation via outbound plugs, to get and enable/disable

   * actions, fire declared events, and access used controllers and/or

   * component usages.

   *

   * @see com.lanco.wdp.IPrivateZhse_displayView for more details

   */

  private final IPrivateZhse_displayView wdThis;

  /**

   * Root node of this controller's context. </p>

   *

   * Provides typed access not only to the elements of the root node

   * but also to all nodes in the context (methods node<i>XYZ</i>())

   * and their currently selected element (methods current<i>XYZ</i>Element()).

   * It also facilitates the creation of new elements for all nodes

   * (methods create<i>XYZ</i>Element()). </p>

   *

   * @see com.lanco.wdp.IPrivateZhse_displayView.IContextNode for more details.

   */

  private final IPrivateZhse_displayView.IContextNode wdContext;

  /**

   * A shortcut for <code>wdThis.wdGetAPI()</code>. </p>

   *

   * Represents the generic API of the generic Web Dynpro counterpart

   * for this controller. </p>

   */

  private final com.sap.tc.webdynpro.progmodel.api.IWDViewController wdControllerAPI;

 

  /**

   * A shortcut for <code>wdThis.wdGetAPI().getComponent()</code>. </p>

   *

   * Represents the generic API of the Web Dynpro component this controller

   * belongs to. Can be used to access the message manager, the window manager,

   * to add/remove event handlers and so on. </p>

   */

  private final com.sap.tc.webdynpro.progmodel.api.IWDComponent wdComponentAPI;

 

  public Zhse_displayView(IPrivateZhse_displayView wdThis)

  {

    this.wdThis = wdThis;

    this.wdContext = wdThis.wdGetContext();

    this.wdControllerAPI = wdThis.wdGetAPI();

    this.wdComponentAPI = wdThis.wdGetAPI().getComponent();

  }

  //@@begin javadoc:wdDoInit()

  /** Hook method called to initialize controller. */

  //@@end

  public void wdDoInit()

  {

    //@@begin wdDoInit()

  wdContext.currentContextElement().setVa_EPC(WDVisibility.NONE);

    //@@end

  }

  //@@begin javadoc:wdDoExit()

  /** Hook method called to clean up controller. */

  //@@end

  public void wdDoExit()

  {

    //@@begin wdDoExit()

  try

  {

  conn.close();

  }

  catch(Exception eg)

  {

  eg.printStackTrace();

  }

    //@@end

  }

  //@@begin javadoc:wdDoModifyView

  /**

   * Hook method called to modify a view just before rendering.

   * This method conceptually belongs to the view itself, not to the

   * controller (cf. MVC pattern).

   * It is made static to discourage a way of programming that

   * routinely stores references to UI elements in instance fields

   * for access by the view controller's event handlers, and so on.

   * The Web Dynpro programming model recommends that UI elements can

   * only be accessed by code executed within the call to this hook method.

   *

   * @param wdThis Generated private interface of the view's controller, as

   *        provided by Web Dynpro. Provides access to the view controller's

   *        outgoing controller usages, etc.

   * @param wdContext Generated interface of the view's context, as provided

   *        by Web Dynpro. Provides access to the view's data.

   * @param view The view's generic API, as provided by Web Dynpro.

   *        Provides access to UI elements.

   * @param firstTime Indicates whether the hook is called for the first time

   *        during the lifetime of the view.

   */

  //@@end

  public static void wdDoModifyView(IPrivateZhse_displayView wdThis, IPrivateZhse_displayView.IContextNode wdContext, com.sap.tc.webdynpro.progmodel.api.IWDView view, boolean firstTime)

  {

    //@@begin wdDoModifyView

    //@@end

  }

  //@@begin javadoc:database()

  /** Declared method. */

  //@@end

  public void database( )

  {

    //@@begin database()

  Connection conn=null;

   Statement sqlstat=null;

  

  try

  {

  //data base connection statements, organise importa, jar files in navigator

  Class.forName("oracle.jdbc.driver.OracleDriver");

  DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());

  conn =DriverManager.getConnection(connectiontext,user,pwd);

  Statement stmt=conn.createStatement();

  sql1= conn.createStatement();

  }

   

  catch (Exception e)

    {

  // TODO: handle exception

  wdComponentAPI.getMessageManager().reportException("Error in database Method",true);

  wdComponentAPI.getMessageManager().reportException(e.toString(),false);

  }

    //@@end

  }

  //@@begin javadoc:onActiondisplay(ServerEvent)

  /** Declared validating event handler. */

  //@@end

  public void onActiondisplay(com.sap.tc.webdynpro.progmodel.api.IWDCustomEvent wdEvent )

  {

    //@@begin onActiondisplay(ServerEvent)

    IPrivateZhse_displayView.IContextElement ele = wdContext.currentContextElement();

    IPrivateZhse_displayView.IKeyElement key = wdContext.currentKeyElement();

    wdContext.nodeKey().invalidate();

  String Queryselect=null;

  if(ele.getBusiness_group() == null|| ele.getBusiness_vertical() == null ||ele.getYear() == null){

  wdComponentAPI.getMessageManager().reportException("* All Values are Mandatory",true);

  }

  else{

  try{

  //wdContext.nodeAmarkantak().invalidate();

  //wdContext.nodeAnpara().invalidate();

  //wdContext.nodeUdipi().invalidate();

    database();

    Statement stmt=conn.createStatement();

    Queryselect="select key1, key2, key3, key4, key5 from hsemonthly_report1";

    //

  // wdComponentAPI.getMessageManager().reportException(Queryselect1,true);

  ResultSet RST= stmt.executeQuery(Queryselect);

  int count=0;

  while(RST.next())

  {

  count=1;

  //wdComponentAPI.getMessageManager().reportSuccess("going inside");

  key.setKey1(RST.getString(1));

  key.setKey2(RST.getString(2));

  key.setKey3(RST.getString(3));

  key.setKey4(RST.getString(4));

  key.setKey5(RST.getString(5));

  }

  if(count ==1){

  

  wdContext.currentContextElement().setVa_EPC(WDVisibility.VISIBLE);

  }else{

  wdContext.currentContextElement().setVa_EPC(WDVisibility.VISIBLE);

// wdContext.currentContextElement().setVa_visible_amrk(WDVisibility.NONE);

// wdContext.currentContextElement().setVa_visible_anpara(WDVisibility.NONE);

// wdContext.currentContextElement().setVa_visible_udipi(WDVisibility.NONE);

  wdComponentAPI.getMessageManager().raiseException("No values exists for the selected date",true);

  }

  }catch(Exception e){

  wdComponentAPI.getMessageManager().raiseException(e.toString(),true);

  wdContext.currentContextElement().setVa_EPC(WDVisibility.VISIBLE);

// wdContext.currentContextElement().setVa_visible_amrk(WDVisibility.NONE);

// wdContext.currentContextElement().setVa_visible_anpara(WDVisibility.NONE);

// wdContext.currentContextElement().setVa_visible_udipi(WDVisibility.NONE);

  }

  try{

   conn.close();

  }

  catch(Exception eg)

  {

   eg.printStackTrace();

   }

  }

    //@@end

  }

  /*

   * The following code section can be used for any Java code that is

   * not to be visible to other controllers/views or that contains constructs

   * currently not supported directly by Web Dynpro (such as inner classes or

   * member variables etc.). </p>

   *

   * Note: The content of this section is in no way managed/controlled

   * by the Web Dynpro Designtime or the Web Dynpro Runtime.

   */

  //@@begin others

  String connectiontext="jdbc:oracle:thin:@lepdb.lancogroup.net:1527:LEP";

  String user="epuser";

  String pwd="userep51";

// String connectiontext="jdbc:oracle:thin:@leapepdv.lancogroup.net:1527:LED";

// String user="epuser";

// String pwd="userep21";

  //String Userid=null;

    Connection conn=null;

    Statement stmt=null;

    Statement sql1=null;

    Statement sql2= null;

  //@@end

}

help me out with this issue

Accepted Solutions (0)

Answers (1)

Answers (1)

michael_voss2
Participant
0 Kudos

Hello!

Since your code provides plenty of places where a NullPointerException might occur, it would help a lot if you could post at least that part of your stack trace that shows the line number of the line where the exception occurs and a hint, where that line is in your code would be helpful, too...

It might be a start not to continue issueing a database request after establishing the connection possibly failed; maybe declaring private fields for the connection and the statement might help, too, so the Connection and the Statement might be accessible fron another method.

Regards

Michael

Former Member
0 Kudos

Hi Michael,

Thanks for your response. After deploying the application I am getting just the null pointer exception,

below is the screenshot.

michael_voss2
Participant
0 Kudos

Hi Shilpi!

Since you catch the exception and show a message in the catch block by just printing the error message, it's almost impossible to tell where exactly you hit the exception. Try removing the try-catch-blocks for a start, so the exception will get propagated to the web dynpro runtime and the complete stack trace will be displayed in the browser. This should give you a pretty good hint on the reason for the exception.

Regards

Michael

govardan_raj
Contributor
0 Kudos

hi shilpi ,

Can u print the stack trace as i had suggested in my earlier threads, so that we can localize this null pointer exception.

after seeing the screen shot , you are getting this exception when the screen is loaded or click of a button ?

Regards

Govardan

michael_voss2
Participant
0 Kudos

Hi Govardan!

I'd guess the exception pops up in Statement stmt=conn.createStatement(); in the method onActiondisplay(), since this method calls database() to initialize the database connection before. But since there seems to be some major confusion about the use of local and instance variables throughout the code, the instance variable conn does not get initialized properly. Instead, the database() method initializes a local variable with the same name conn with a database connection that gets dumped right away at the end of the method. So maybe Shilpi might want to have a closer look at the code and maybe rewrite some of it making proper use of instance variables. But this is only a guess, let's wait for some stack trace.

Regards

Michael

Former Member
0 Kudos

Hi All,

Thank you for your quick response.

i have checked my code it is not reading the try block and executing the catch block directly. Is there any way I can rectify it?

I don't know the code to print the stack, can you give the code for that?

below is my code, I made few changes but the same problem:

// ---------------------------------------------------------------------------

// This file has been generated partially by the Web Dynpro Code Generator.

// MODIFY CODE ONLY IN SECTIONS ENCLOSED BY @@begin AND @@end.

// ALL OTHER CHANGES WILL BE LOST IF THE FILE IS REGENERATED.

// ---------------------------------------------------------------------------

package com.lanco;

//

// IMPORTANT NOTE:

// _ALL_ IMPORT STATEMENTS MUST BE PLACED IN THE FOLLOWING SECTION ENCLOSED

// BY @@begin imports AND @@end. FURTHERMORE, THIS SECTION MUST ALWAYS CONTAIN

// AT LEAST ONE IMPORT STATEMENT (E.G. THAT FOR IPrivateZhse_displayView).

// OTHERWISE, USING THE ECLIPSE FUNCTION "Organize Imports" FOLLOWED BY

// A WEB DYNPRO CODE GENERATION (E.G. PROJECT BUILD) WILL RESULT IN THE LOSS

// OF IMPORT STATEMENTS.

//

//@@begin imports

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.Statement;

import java.util.Calendar;

import com.lanco.wdp.IPrivateZhse_displayView;

import com.sap.tc.webdynpro.progmodel.api.WDVisibility;

//@@end

//@@begin documentation

//@@end

public class Zhse_displayView

{

  /**

   * Logging location.

   */

  private static final com.sap.tc.logging.Location logger =

    com.sap.tc.logging.Location.getLocation(Zhse_displayView.class);

  static

  {

    //@@begin id

    String id = "$Id$";

    //@@end

    com.sap.tc.logging.Location.getLocation("ID.com.sap.tc.webdynpro").infoT(id);

  }

  /**

   * Private access to the generated Web Dynpro counterpart

   * for this controller class.  </p>

   *

   * Use <code>wdThis</code> to gain typed access to the context,

   * to trigger navigation via outbound plugs, to get and enable/disable

   * actions, fire declared events, and access used controllers and/or

   * component usages.

   *

   * @see com.lanco.wdp.IPrivateZhse_displayView for more details

   */

  private final IPrivateZhse_displayView wdThis;

  /**

   * Root node of this controller's context. </p>

   *

   * Provides typed access not only to the elements of the root node

   * but also to all nodes in the context (methods node<i>XYZ</i>())

   * and their currently selected element (methods current<i>XYZ</i>Element()).

   * It also facilitates the creation of new elements for all nodes

   * (methods create<i>XYZ</i>Element()). </p>

   *

   * @see com.lanco.wdp.IPrivateZhse_displayView.IContextNode for more details.

   */

  private final IPrivateZhse_displayView.IContextNode wdContext;

  /**

   * A shortcut for <code>wdThis.wdGetAPI()</code>. </p>

   *

   * Represents the generic API of the generic Web Dynpro counterpart

   * for this controller. </p>

   */

  private final com.sap.tc.webdynpro.progmodel.api.IWDViewController wdControllerAPI;

 

  /**

   * A shortcut for <code>wdThis.wdGetAPI().getComponent()</code>. </p>

   *

   * Represents the generic API of the Web Dynpro component this controller

   * belongs to. Can be used to access the message manager, the window manager,

   * to add/remove event handlers and so on. </p>

   */

  private final com.sap.tc.webdynpro.progmodel.api.IWDComponent wdComponentAPI;

 

  public Zhse_displayView(IPrivateZhse_displayView wdThis)

  {

    this.wdThis = wdThis;

    this.wdContext = wdThis.wdGetContext();

    this.wdControllerAPI = wdThis.wdGetAPI();

    this.wdComponentAPI = wdThis.wdGetAPI().getComponent();

  }

  //@@begin javadoc:wdDoInit()

  /** Hook method called to initialize controller. */

  //@@end

  public void wdDoInit()

  {

    //@@begin wdDoInit()

  //IPrivateZhse_display.IContextElement dates = wdContext.currentContextElement();

    

  wdContext.currentContextElement().setVa_EPC(WDVisibility.NONE);

    //@@end

  }

  //@@begin javadoc:wdDoExit()

  /** Hook method called to clean up controller. */

  //@@end

  public void wdDoExit()

  {

    //@@begin wdDoExit()

  try

  {

  conn.close();

  }

  catch(Exception eg)

  {

  eg.printStackTrace();

  }

    //@@end

  }

  //@@begin javadoc:wdDoModifyView

  /**

   * Hook method called to modify a view just before rendering.

   * This method conceptually belongs to the view itself, not to the

   * controller (cf. MVC pattern).

   * It is made static to discourage a way of programming that

   * routinely stores references to UI elements in instance fields

   * for access by the view controller's event handlers, and so on.

   * The Web Dynpro programming model recommends that UI elements can

   * only be accessed by code executed within the call to this hook method.

   *

   * @param wdThis Generated private interface of the view's controller, as

   *        provided by Web Dynpro. Provides access to the view controller's

   *        outgoing controller usages, etc.

   * @param wdContext Generated interface of the view's context, as provided

   *        by Web Dynpro. Provides access to the view's data.

   * @param view The view's generic API, as provided by Web Dynpro.

   *        Provides access to UI elements.

   * @param firstTime Indicates whether the hook is called for the first time

   *        during the lifetime of the view.

   */

  //@@end

  public static void wdDoModifyView(IPrivateZhse_displayView wdThis, IPrivateZhse_displayView.IContextNode wdContext, com.sap.tc.webdynpro.progmodel.api.IWDView view, boolean firstTime)

  {

    //@@begin wdDoModifyView

    //@@end

  }

  //@@begin javadoc:database()

  /** Declared method. */

  //@@end

  public void database( )

  {

    //@@begin database()

  Connection conn=null;

  Statement sqlstat=null;

  

  try

  {

  //data base connection statements, organise importa, jar files in navigator

  Class.forName("oracle.jdbc.driver.OracleDriver");

  DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());

  conn =DriverManager.getConnection(connectiontext,user,pwd);

  Statement stmt=conn.createStatement();

  sql1= conn.createStatement();

  }

   

  catch (Exception e)

    {

  // TODO: handle exception

  wdComponentAPI.getMessageManager().reportException("Error in database Method",true);

  wdComponentAPI.getMessageManager().reportException(e.toString(),false);

  }

    //@@end

  }

  //@@begin javadoc:onActiondisplay(ServerEvent)

  /** Declared validating event handler. */

  //@@end

  public void onActiondisplay(com.sap.tc.webdynpro.progmodel.api.IWDCustomEvent wdEvent )

  {

    //@@begin onActiondisplay(ServerEvent)

    IPrivateZhse_displayView.IContextElement ele = wdContext.currentContextElement();

    IPrivateZhse_displayView.IKeyElement key = wdContext.currentKeyElement();

    wdContext.nodeKey().invalidate();

  String Queryselect=null;

  if(ele.getBusiness_group() == null|| ele.getBusiness_vertical() == null ||ele.getYear() == null){

  wdComponentAPI.getMessageManager().reportException("* All Values are Mandatory",true);

  }

  else{

  try{

  wdContext.nodeKey().invalidate();

    database();

    Statement stmt=conn.createStatement();

    Queryselect="select KEY1, KEY2, KEY3, KEY4, KEY5 from HSEMONTHLY_REPORT1";

   

  wdComponentAPI.getMessageManager().reportException(Queryselect,true);

  ResultSet RST= stmt.executeQuery(Queryselect);

  int count=0;

  while(RST.next())

  {

  count=1;

  wdComponentAPI.getMessageManager().reportSuccess("going inside");

  key.setKey1(RST.getString(1));

  key.setKey2(RST.getString(2));

  key.setKey3(RST.getString(3));

  key.setKey4(RST.getString(4));

  key.setKey5(RST.getString(5));

  }

  if(count ==1)

  {

  wdContext.currentContextElement().setVa_EPC(WDVisibility.VISIBLE);

  }

  else

  {

  wdContext.currentContextElement().setVa_EPC(WDVisibility.VISIBLE);

  wdComponentAPI.getMessageManager().raiseException("No values exists for the selected date",true);

  }

  }

  catch(Exception eg)

  {

  eg.printStackTrace();

  wdComponentAPI.getMessageManager().raiseException(eg.toString(),true);

  wdContext.currentContextElement().setVa_EPC(WDVisibility.VISIBLE);

  wdComponentAPI.getMessageManager().raiseException("Error", false);

  }

  }

    //@@end

  }

  /*

   * The following code section can be used for any Java code that is

   * not to be visible to other controllers/views or that contains constructs

   * currently not supported directly by Web Dynpro (such as inner classes or

   * member variables etc.). </p>

   *

   * Note: The content of this section is in no way managed/controlled

   * by the Web Dynpro Designtime or the Web Dynpro Runtime.

   */

  //@@begin others

  String connectiontext="jdbc:oracle:thin:@lepdb.lancogroup.net:1527:LEP";

  String user="epuser";

  String pwd="userep51";

// String connectiontext="jdbc:oracle:thin:@leapepdv.lancogroup.net:1527:LED";

// String user="epuser";

// String pwd="userep21";

  //String Userid=null;

    Connection conn=null;

    Statement stmt=null;

    Statement sql1=null;

    Statement sql2= null;

  //@@end

}

michael_voss2
Participant
0 Kudos

Hello Shilpi!

Remove the try-catch-Statements (comment out the try and catch keywords and the corresponding braces, not the code inside of these), then you'll get the complete stack trace printed out when the error occurs. Alternatively you can print the errors stack trace to some log using the Exception.printStackTrace() method.

As posted earlier, if might prove helpful to rewrite (not modify) your code regarding the use of local and instance variables, especially conn and stmt. Maybe you'd like to remove the lines

Connection conn=null;

Statement sqlstat=null;

from the database() method for a start.

Regards

Michael

Former Member
0 Kudos

Hi Michael,

I have tried the writing of code again, it is showing same error. same database code is working for another application. it should fetch the data from the database as it is doing for another application.

michael_voss2
Participant
0 Kudos

Hi Shilpi!

I rearranged your code a little bit, changed some variable names and addes some "this." and some comments to improve clarity. Maybe you'll se why I assume where the NullPointerException is going to happen:

// Declaration of instance variables !

  String connectiontext="jdbc:oracle:thin:@someserver:1527:something";
  String user = "someuser";
  String pwd = "somepassword";
  Connection conn = null;
  Statement stmt = null;
  Statement sql1 = null;
  Statement sql2 = null;

  public void onActiondisplay(com.sap.tc.webdynpro.progmodel.api.IWDCustomEvent wdEvent )
  {
    //@@begin onActiondisplay(ServerEvent)
    IPrivateZhse_displayView.IContextElement ele = wdContext.currentContextElement();
    IPrivateZhse_displayView.IKeyElement key = wdContext.currentKeyElement();

    wdContext.nodeKey().invalidate();

    String Queryselect = null;

    if(ele.getBusiness_group() == null|| ele.getBusiness_vertical() == null ||ele.getYear() == null){
  wdComponentAPI.getMessageManager().reportException("* All Values are Mandatory",true);
} else{
  try {
   wdContext.nodeKey().invalidate(); // not necessary, done justbefore
  
   // calling the method database() to initialize connection
   this.database();

   // The NullPointerException will occur in the following statement since this.conn will always be null !
      Statement stmt = this.conn.createStatement(); // creating a new variable for the statement instead of using the instance variable here
   Queryselect="select KEY1, KEY2, KEY3, KEY4, KEY5 from HSEMONTHLY_REPORT1";
  
   // wdComponentAPI.getMessageManager().reportException(Queryselect,true); // you'd rather log this to an appropriate logger !
  
   ResultSet RST = stmt.executeQuery(Queryselect);
   int count=0;
  
   while(RST.next()) {
    count=1;
    // wdComponentAPI.getMessageManager().reportSuccess("going inside");
    key.setKey1(RST.getString(1));
    key.setKey2(RST.getString(2));
    key.setKey3(RST.getString(3));
    key.setKey4(RST.getString(4));
    key.setKey5(RST.getString(5));
   }
  
   if(count == 1) {
    wdContext.currentContextElement().setVa_EPC(WDVisibility.VISIBLE);
   } else {
    wdContext.currentContextElement().setVa_EPC(WDVisibility.VISIBLE);
    wdComponentAPI.getMessageManager().raiseException("No values exists for the selected date",true);
   };
  } catch(Exception eg) {
   eg.printStackTrace(); // Prints to STDOUT, log this instead !
   // This is what you see in the gui
   wdComponentAPI.getMessageManager().raiseException(eg.toString(),true);
   wdContext.currentContextElement().setVa_EPC(WDVisibility.VISIBLE);
   wdComponentAPI.getMessageManager().raiseException("Error", false);
  }
}
//@@end
}


public void database( )
{
//@@begin database()
// I renamed the local variables in this to improve clarity
Connection localConnection = null;
Statement localStatement = null;

try
{
//data base connection statements, organise importa, jar files in navigator
Class.forName("oracle.jdbc.driver.OracleDriver");
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());

// local variable gets used since java will alway use the variable with the smallest scope !
// This will lead to the result that this.conn will not be initializes upon return to this.onActiondisplay
localConnection = DriverManager.getConnection(this.connectiontext, this.user, this.pwd);
Statement localStatement = localConnection.createStatement();
this.sql1 = localConnection.createStatement();
} catch (Exception e) {
  // TODO: handle exception
  wdComponentAPI.getMessageManager().reportException("Error in database Method", true);
  wdComponentAPI.getMessageManager().reportException(e.toString(),false);
}
    //@@end

  }

The problem is the use of local variables (especially conn which I renamed to localConnection) inside the database() method opposed to using the instance variable conn in the onActionDisplay() method. Maybe you'll be able to verify that the exception happens at this very location when you see a stack trace of your exception.

This problem is not WebDynpro-related, but basic Java programming, which is why I asked you to rewrite the code.

In my opinion, it's always preferrable to send messages using "this." when intendig to refer to instance variables or instance methods instead of using these fields directly. At least, mistakes like these can be avoided...

Regards

Michael


Former Member
0 Kudos

hi Michael,

Thank you so much for your help. I have changed the code as you have said, still I am facing the same issue. I have rebuild the project and below is the screenshot, at the bottom-left there is a log of error, i dont know the way to see the details. can you help me in that?

michael_voss2
Participant
0 Kudos

Hello Shilpi!

Yes, I would expect the exception to occur with my changes in place since all I did (and intended to do) was making the reason for the error more obvious: Your code in the method database() does not initialize the instance variable conn prior to its use in the method onActiondisplay()since you mess up the use of (method-)local and instance variables. If you change the database() method to something like

public void database( )

  {

  //@@begin database()

  try {

       //Establish database connection and create some statements

       Class.forName("oracle.jdbc.driver.OracleDriver");

       DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());

       this.conn = DriverManager.getConnection(connectiontext,user,pwd);

       this.stmt = this.conn.createStatement();

       this.sql1= this.conn.createStatement();

  } catch (Exception e) {

       // TODO: handle exception

       wdComponentAPI.getMessageManager().reportException("Exception connecting to database: " + e, false);

  }

    //@@end

  }

your code might work.

But again, this is just a guess; to be sure of the exact reason we need to see your stack trace. As I mentioned before, remove the try-catch-statements and you will see where the exception occurs and correct it properly. When you do this, the relevant part of your onActiondisplay() method might look like this (and I strongly suggest to make this change first, then have a look at the stack trace and revert the change before finally changing the database() method):

...

// Removing try-catch to make stack trace visible

//  try {

     wdContext.nodeKey().invalidate();

     this.database();

//     this.stmt = conn.createStatement(); // not necessary, initialized inside the database() method

     Queryselect = "select KEY1, KEY2, KEY3, KEY4, KEY5 from HSEMONTHLY_REPORT1";

   

//     wdComponentAPI.getMessageManager().reportException(Queryselect,true); // use logging instead

     ResultSet RST= this.stmt.executeQuery(Queryselect);

     int count = 0;

     while(RST.next()) {

          count = count + 1;

//          wdComponentAPI.getMessageManager().reportSuccess("going inside");  // use logging instead

          key.setKey1(RST.getString(1));

          key.setKey2(RST.getString(2));

          key.setKey3(RST.getString(3));

          key.setKey4(RST.getString(4));

          key.setKey5(RST.getString(5));

     }

     if (count > 0) {

          wdContext.currentContextElement().setVa_EPC(WDVisibility.VISIBLE);

     } else {

          wdContext.currentContextElement().setVa_EPC(WDVisibility.VISIBLE);

          wdComponentAPI.getMessageManager().raiseException("No values exists for the selected date",true);

     }

// remove try-catch to make stack trace visible

//  } catch(Exception eg) {

//     eg.printStackTrace();

//     wdComponentAPI.getMessageManager().raiseException(eg.toString(),true);

//     wdContext.currentContextElement().setVa_EPC(WDVisibility.VISIBLE);

//     wdComponentAPI.getMessageManager().raiseException("Error", false);

//     }

...

Regards

Michael

Sharathmg
Active Contributor
0 Kudos

Hello,

As I understand, Micheal is assisting you in locating the exact line of code where this NULL Pointer exception is being triggered.

So, try to avoid printing the custom message and allow the screen/framework to through the complete error stack trace. It seems like a Java beginner issue and on careful inspection, you may be able to locate the object which is null.

Regards,

Sharath