title: Why do I keep Getting null Pointer Exception in Serial port communication Program
body: <p>Okay so I have a couple of problems here first I keep getting a nullPointerException when trying to connect to com port 3, I have tried this several different ways, first by just selecting the port and going after it secondly by searching for the port and trying it. The second time around I kept getting this 32 bit 64 bit mismatch exception for my RXTX lib so I fixed that and then came up with this error</p>
  
  <pre><code>WARNING:  RXTX Version mismatch
         Jar version = RXTX-2.2pre1
         native lib Version = RXTX-2.2pre2
  Failed to open COM3(java.lang.NullPointerException)
  Failed to open COM3(java.lang.NullPointerException)
  </code></pre>
  
  <p>Which I can't seem to figure out because I got both of them from the same place. However My issue still lies with the Null Pointer Exception so here is a view of my code</p>
  
  <pre><code>import javax.swing.*;
  import java.awt.event.*;
  import java.awt.*;
  import javax.swing.border.*;
  
  public class SPMRV2 extends MyFrame{
  UserSerialV2 communicator = null;
  
  //combo Box for Com port selection
  public JComboBox comBox = new JComboBox(new String[] {"COM1", "COM2", "COM3", "COM4", "COM5"});
  private JButton selectBtn = new JButton("Select");
  
  //Buttons or the starting and stopping of the program Start will initialize the   program stop will close the port for communication
  private JButton startBtn = new JButton("Connect");
  private JButton stopBtn = new JButton("Disconnect");
  
      //message Area for log
      private JTextArea logDisplay = new JTextArea(" ", 200, 45);
      private JTextField newTextFile = new JTextField();
      private JLabel fileLabel = new JLabel("Please Enter The File You Wish To Log To: \n");
  
  public SPMRV2(){
      initComponents();
      createObjects();
  
  }
  
  public void createObjects(){
      communicator = new UserSerialV2();
  }
  
  public void initComponents(){
      //set Button Listeners
      ButtonListener selected = new ButtonListener();
      startBtn.addActionListener(selected);
      stopBtn.addActionListener(selected);
      selectBtn.addActionListener(selected);
  
      JPanel comSelect = new JPanel();
          comSelect.setLayout(new GridLayout(4,1));
          comSelect.setBorder(new TitledBorder("Select Your Com Port"));
          comSelect.add(comBox);
          comSelect.add(fileLabel);
          comSelect.add(newTextFile);
          comSelect.add(selectBtn);
  
      JPanel action = new JPanel();
          action.setLayout(new FlowLayout());
          action.setBorder(new TitledBorder("Start/Stop console"));
          action.add(startBtn);
          action.add(stopBtn);
  
      JPanel leftContainer = new JPanel();
          leftContainer.setLayout(new BorderLayout());
          leftContainer.add(comSelect, BorderLayout.NORTH);
          leftContainer.add(action, BorderLayout.SOUTH);
  
      JPanel rightContainer = new JPanel();
          rightContainer.setLayout(new FlowLayout());
          rightContainer.setBorder(new TitledBorder("Members Logged"));
          rightContainer.add(logDisplay);
  
      JPanel wrapper = new JPanel();
          wrapper.setLayout(new BorderLayout());
          wrapper.add(leftContainer, BorderLayout.WEST);
          wrapper.add(rightContainer, BorderLayout.EAST);
  
      add(wrapper);
  
  }   
  
   public static void main(String args[]) {
      java.awt.EventQueue.invokeLater(new Runnable() {
          public void run() {
            new SPMRV2().setVisible(true);
          }
      });
   }
  
      //Start/Stop/Select/Quit Button Listener Class
      class ButtonListener implements ActionListener{
          String userFile = "";
          String newComPort = "";
              public void actionPerformed(ActionEvent e){
                  if(e.getSource() == selectBtn){
                      comBox.addItemListener(new ItemListener(){
                          public void itemStateChanged(ItemEvent e){
                              }
  
                      });
                          newComPort = (String)comBox.getSelectedItem();
                          userFile = newTextFile.getText();
                             communicator.searchForPorts(newComPort);
                             logDisplay.append(communicator.searchForPorts(newComPort));
                          logDisplay.append("You are going to     be communicating through Comm Port: " + newComPort + "\n");
                          logDisplay.append("And you will be     Logging info to text File: " + userFile + "\n");
          }
  
          if(e.getSource() == startBtn){
               communicator.initiate(newComPort);
                  if (communicator.getConnected() == true){
                      if (communicator.readerStream() == true){
                          communicator.startListener();
                          communicator.logging(userFile);
                      }
                  }
  
          }else if(e.getSource() == stopBtn){
              communicator.disconnect();
              }
  
  
      }
  
      }
  
  
  }
  </code></pre>
  
  <p>this is the gui setup that I am using and the following is my serial program</p>
  
  <pre><code>import gnu.io.*;
  import java.awt.Color;
  import java.io.IOException;
  import java.io.InputStream;
  import java.io.OutputStream;
  import java.util.Enumeration;
  import java.util.HashMap;
  import java.util.TooManyListenersException;
  
  public class UserSerialV2 extends SPMR implements SerialPortEventListener{
  //create string to store exception readout in
  String excepText = "";
  public boolean bConnected = false;
  
  /*
  Creates a file and additional info for serial logging storage
  */
  public static String file = "";
  public static String data = "";
  public static final java.util.Date LOG_DATE = new java.util.Date();
  
  //for containing the ports that will be found
  private Enumeration serialPorts = null;
  //map the port names to CommPortIdentifiers
  private HashMap portMap = new HashMap();
  
  //this is the object that contains the opened port
  private CommPortIdentifier selectedPortIdentifier = null;
  private SerialPort serialPort = null;
  
  //input and output streams for sending and receiving data
  public InputStream input = null;
  private OutputStream output = null;
  
  //the timeout value for connecting with the port
  final static int TIMEOUT = 5000;
  
  //some ascii values for for certain things
  final static int SPACE_ASCII = 32;
  final static int DASH_ASCII = 45;
  final static int NEW_LINE_ASCII = 10;
  
      public UserSerialV2(){
  
      }
  
      public String searchForPorts(String userComm){
      serialPorts = CommPortIdentifier.getPortIdentifiers();
  
      while (serialPorts.hasMoreElements()){
          CommPortIdentifier currentPort = (CommPortIdentifier)serialPorts.nextElement();
  
          //get only serial ports
          if (currentPort.getName() == userComm){             
              portMap.put(currentPort.getName(), currentPort);
                  data = "Found Com Port 3";
  
          }
      }
      return data;
   }
  
  public void initiate(String comPort){
          String selectedPort = comPort;
      selectedPortIdentifier = (CommPortIdentifier)portMap.get(selectedPort);
  
      CommPort commPort = null;
  
      try{
          //the method below returns an object of type CommPort
          commPort = selectedPortIdentifier.open("User Serial APP", TIMEOUT);
          //the CommPort object can be casted to a SerialPort object
          serialPort = (SerialPort)commPort;
              serialPort.setSerialPortParams(9600, 8, 1, 0);
  
              setConnected(true);
          //logging
          data = selectedPort + " opened successfully.";
  
          // //CODE ON SETTING BAUD RATE ETC OMITTED
               // try {
                  // serialPort.setSerialPortParams(9600,
              // SerialPort.DATABITS_8,
              // SerialPort.STOPBITS_1,
              // SerialPort.PARITY_NONE);
          // } catch (UnsupportedCommOperationException e){
              // System.out.println(e);
          // }//end try catch block
  
      }
      catch (PortInUseException e){
          excepText = selectedPort + " is in use. (" + e.toString() + ")";
              System.out.println(excepText);
      }
      catch (Exception e){
          excepText = "Failed to open " + selectedPort + "(" + e.toString() + ")";
              System.out.println(excepText);
      }
  }
  
      //method to collect input from the port
  public boolean readerStream() {
      //boolean value variable for input stream
          boolean success = false;
          try{
              input = serialPort.getInputStream();
          success = true;
          return success;
      }catch(IOException e){
          excepText = "I/O Streams Failed To Open" + "(" + e.toString() +         ")";
          System.out.println(excepText);
          return success;
      }
  }//end readerStream
  
  //method to start listener when user connects to port
  public void startListener(){
      try{
          serialPort.addEventListener(this);
          serialPort.notifyOnDataAvailable(true);
      }catch(TooManyListenersException e){
          excepText = "Too many listeners" + "(" + e.toString() + ")";
          System.out.println(excepText);
      }   
  }
  
  //Method to disconnect from the serial port when the user is finished with logging 
  public void disconnect(){
      try{
          serialPort.removeEventListener();
          serialPort.close();
          input.close();
          data = "Disconnected";
          setConnected(false);
      }catch(Exception e){
          excepText = "(" + e.toString() + ")";
          System.out.println("Disconnect Problem " + excepText);
      }
  }
  
  public void serialEvent(SerialPortEvent event){
      if (event.getEventType() == SerialPortEvent.DATA_AVAILABLE){
          try{
                byte singleData = (byte)input.read();
  
              if (singleData != NEW_LINE_ASCII){
                  this.data = new String(new byte[] {singleData});
              }
              else
              {
                  this.data = "\n";
              }
          }catch(Exception e){
              excepText = "(" + e.toString() + ")";
              System.out.println("Serial Event Problem " + excepText);
          }
      }
  }
  
  final public boolean getConnected()
  {
      return bConnected;
  }
  
  public void setConnected(boolean bConnected)
  {
      this.bConnected = bConnected;
  }
  
  public String logging(String file){
      UserLogFile log = new UserLogFile();
                      log.openFile(file);
                      log.addLog(data + LOG_DATE);
                      log.closeFile();
      return data;
  }
  </code></pre>
  
  <p>}</p>
  
  <p>I have asked this question before but can't seem to get any responses, any body got any ideas as to what could be causing the problem???</p>
  
  <p>Thanks, </p>
  
  <p>oh and userlogFile is mentioned in the code as well it was just a simple writing class I was using to pass information to a text file of the users that Logged in.</p>