Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 7 of 7

Thread: nullpointer exception trying to write to file

  1. #1
    Junior Member
    Join Date
    Aug 2014
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default nullpointer exception trying to write to file

    I've been closely following a tutorial series, and as far as I can tell my code is exactly the same, but not functioning. The app throws a nullpointer exception here on "controller.saveToFile(fileChooser.getSelectedFile ());"

    // Export data item
    		exportDataItem.addActionListener(new ActionListener() {
    			public void actionPerformed(ActionEvent e) {
    				if (fileChooser.showSaveDialog(MainFrame.this) == JFileChooser.APPROVE_OPTION) {
    					try {
    						controller.saveToFile(fileChooser.getSelectedFile());
     
    					} catch (IOException e1) {
    						JOptionPane.showMessageDialog(MainFrame.this,
    								"Could not save data to file.", "Error",
    								JOptionPane.ERROR_MESSAGE);
    					}
     
    				}
     
    			}
    		});

    controller save method:

    public void saveToFile(File file) throws IOException {
    		db.saveToFile(file);
    	}

    database save method:

    	public void saveToFile(File file) throws IOException {
    		FileOutputStream fos = new FileOutputStream(file);
    		ObjectOutputStream oos = new ObjectOutputStream(fos);
     
    		Person[] persons = people.toArray(new Person[people.size()]);
     
    		oos.writeObject(persons);
     
    		oos.close();
     
    	}

    there are no errors popping up in the code, and I dont understand why there is a null pointer exception when Im saving this file.

    please let me know if I need to upload more code, or if I just did something stupid here.

    thanks!


  2. #2
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,017
    My Mood
    Mellow
    Thanks
    182
    Thanked 644 Times in 631 Posts

    Default Re: nullpointer exception trying to write to file

    Welcome to the Forum! Thanks for taking the time to learn to post code correctly, and if you haven't already, please read this topic to see other useful info for newcomers.

    Please post the entire error message/stack trace, copied and pasted into a post from just as it appears at your end. See if you can pare the code down to a simple runnable example you could post to demonstrate the problem: open a file using fileChooser() and write a single line to it.

  3. #3
    Junior Member
    Join Date
    Aug 2014
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: nullpointer exception trying to write to file

    Here is the stacktrace:

    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    	at gui.MainFrame$6.actionPerformed(MainFrame.java:145)
    	at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
    	at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
    	at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
    	at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
    	at javax.swing.AbstractButton.doClick(Unknown Source)
    	at javax.swing.plaf.basic.BasicMenuItemUI.doClick(Unknown Source)
    	at javax.swing.plaf.basic.BasicMenuItemUI$Handler.mouseReleased(Unknown Source)
    	at java.awt.Component.processMouseEvent(Unknown Source)
    	at javax.swing.JComponent.processMouseEvent(Unknown Source)
    	at java.awt.Component.processEvent(Unknown Source)
    	at java.awt.Container.processEvent(Unknown Source)
    	at java.awt.Component.dispatchEventImpl(Unknown Source)
    	at java.awt.Container.dispatchEventImpl(Unknown Source)
    	at java.awt.Component.dispatchEvent(Unknown Source)
    	at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
    	at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
    	at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
    	at java.awt.Container.dispatchEventImpl(Unknown Source)
    	at java.awt.Window.dispatchEventImpl(Unknown Source)
    	at java.awt.Component.dispatchEvent(Unknown Source)
    	at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    	at java.awt.EventQueue.access$200(Unknown Source)
    	at java.awt.EventQueue$3.run(Unknown Source)
    	at java.awt.EventQueue$3.run(Unknown Source)
    	at java.security.AccessController.doPrivileged(Native Method)
    	at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    	at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    	at java.awt.EventQueue$4.run(Unknown Source)
    	at java.awt.EventQueue$4.run(Unknown Source)
    	at java.security.AccessController.doPrivileged(Native Method)
    	at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    	at java.awt.EventQueue.dispatchEvent(Unknown Source)
    	at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    	at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    	at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    	at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    	at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    	at java.awt.EventDispatchThread.run(Unknown Source)

  4. #4
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,017
    My Mood
    Mellow
    Thanks
    182
    Thanked 644 Times in 631 Posts

    Default Re: nullpointer exception trying to write to file

    Very helpful.

    Based on these lines (and a little experience):
    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    	at gui.MainFrame$6.actionPerformed(MainFrame.java:145)
    	at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
    look at line 145 which should be in the actionPerformed() method. It appears a button is being fired (I'll call it 'myButton') that has not been initialized before being used, as in:

    myButton = new JButton();

    Figure out which button (or whatever it is) is being complained about and backtrack through the code to determine why it was declared but not initialized (in the constructor, maybe) and fix it.

  5. #5
    Junior Member
    Join Date
    Aug 2014
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: nullpointer exception trying to write to file

    ok I initialized my controller which fixed the nullpointer exception. my save method seems to work (creates a file on my desktop). but when I try and import and then refresh my table model, the code runs but nothing displays. my tableModel.refresh method fires the data changed method in my table.

    --- Update ---

    Load method in MainFrame:

    // Import data item
    		importDataItem.addActionListener(new ActionListener() {
    			public void actionPerformed(ActionEvent e) {
    				if (fileChooser.showOpenDialog(MainFrame.this) == JFileChooser.APPROVE_OPTION) {
    					try {
    						Controller controller = new Controller();
    						controller.loadFromFile(fileChooser.getSelectedFile());
    						tablePanel.refresh();
    						System.out.println("tableModel refreshed");
    					} catch (IOException e1) {
    						JOptionPane.showMessageDialog(MainFrame.this,
    								"Could not load data from file.", "Error",
    								JOptionPane.ERROR_MESSAGE);
    					}
    				}
    				tablePanel.refresh();
    			}
    		});


    load method in controller:

    public void loadFromFile(File file) throws IOException {
    		db.loadToFile(file);
    	}

    load method in database db:

    	public void loadToFile(File file) throws IOException {
    		FileInputStream fis = new FileInputStream(file);
    		ObjectInputStream ois = new ObjectInputStream(fis);
     
    		Person[] persons;
    		try {
    			people.clear();
    			persons = (Person[]) ois.readObject();
    			people.addAll(Arrays.asList(persons));
    		} catch (ClassNotFoundException e) {
    			e.printStackTrace();
    		}
     
    		ois.close();
     
    	}

  6. #6
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,017
    My Mood
    Mellow
    Thanks
    182
    Thanked 644 Times in 631 Posts

    Default Re: nullpointer exception trying to write to file

    when I try and import and then refresh my table model, the code runs but nothing displays
    Does the table display before the refresh? The table is a component, the table model is a behind the scenes description of the table, so the first step is to reliably display the component. Can you do the first step?

  7. #7
    Junior Member
    Join Date
    Aug 2014
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: nullpointer exception trying to write to file

    Quote Originally Posted by GregBrannon View Post
    Does the table display before the refresh? The table is a component, the table model is a behind the scenes description of the table, so the first step is to reliably display the component. Can you do the first step?
    Here is my TablePanel.java:

    package gui;
     
    import java.awt.BorderLayout;
    import java.util.List;
     
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
     
    import model.Person;
     
    public class TablePanel extends JPanel {
     
    	private static final long serialVersionUID = -5068640091114058027L;
     
    	private JTable table;
    	private PersonTableModel tableModel;
     
    	public TablePanel() {
     
    		tableModel = new PersonTableModel();
    		table = new JTable(tableModel);
     
    		setLayout(new BorderLayout());
     
    		add(new JScrollPane(table), BorderLayout.CENTER);
    	}
     
    	public void setData(List<Person> db) {
    		tableModel.setData(db);
    	}
     
    	public void refresh() {
    		tableModel.fireTableDataChanged();
    	}
     
    }

    This is starting to drive me insane, I can't figure this shit out. When I add an element and use refresh it works just fine. I don't know if it's just not displaying or if it's not loading anything at all.

    --- Update ---

    Quote Originally Posted by GregBrannon View Post
    Does the table display before the refresh? The table is a component, the table model is a behind the scenes description of the table, so the first step is to reliably display the component. Can you do the first step?
    The table column names display but no data.

    --- Update ---

    Solved! This was a response from John Purcell of caveofprogramming.com:

    You're doing this in MainFrame.java: final Controller controller = new Controller();
    So you're creating a new controller, creating a new variable at local scope overshadowing the one at class scope that you actually need to be using. What you need is this: controller = new Controller();
    The controller that you then try to use is the instance variable, which was not set to new anything.
    Then to fix the null pointer, you added more new controller statements, creating new databases all over the place
    I think every programmer has made this mistake sometime -- declaring a new local variable by mistake, instead of initializing the class-level one. You have to pay careful attention to what those null pointer exceptions tell you --- otherwise they extract dire payment. They are usually easy to fix once you know how.

Similar Threads

  1. nullpointer exception when adding Object to ArrayList
    By bartolio in forum What's Wrong With My Code?
    Replies: 14
    Last Post: January 20th, 2013, 11:17 AM
  2. NullPointer exception error
    By davx in forum What's Wrong With My Code?
    Replies: 2
    Last Post: November 18th, 2012, 12:08 PM
  3. NullPointer Exception problem
    By anshu in forum What's Wrong With My Code?
    Replies: 3
    Last Post: June 26th, 2012, 06:38 AM
  4. java.lang.nullpointer exception in beginner code
    By Bobba in forum What's Wrong With My Code?
    Replies: 7
    Last Post: May 6th, 2012, 05:37 PM
  5. [SOLVED] Nullpointer exception when sending string
    By treshr in forum What's Wrong With My Code?
    Replies: 3
    Last Post: August 26th, 2011, 04:36 AM