Object Serialization and Reading

R

Rich Wahl

So I threw out my Idea about using JDBC, and went to Serialization of
a Class and using just a File/Object reader/writer.

I have this snippet of code running when I click a View button, I want
the code to read in the Objects from a File and then output them into
a TextField on the Frame. The Code is Syntaxically correct, But when
it gets to the
"outputField.append(tempCritter.toString());" line.
It throws a null pointer exception. But The tempCritter cant be null
if it gets to that line.

Am I understanding Serializable wrong? Thanks in advance for any
advice.

Here is my Code for the ViewButton. (The Index prints are just to
'debug' to make sure they are being called and to find out where the
problem really is)
----------------------------
if (event.getActionCommand() == "View") {
try {
ObjectInputStream
instream = new ObjectInputStream( new
FileInputStream("CritterDB.rdb"));
int index = 0;
System.out.println(index);
CritterClass tempCritter = new CritterClass();
while((tempCritter = (CritterClass)instream.readObject()) != null) {
outputField.append(tempCritter.toString());
index++;
System.out.println(index);
}//close while
instream.close();
} // Try in View

catch (Exception d) {
System.out.println(d.getMessage());
d.printStackTrace();
}
}// View Button

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

And here is my Class Definition.

import java.io.Serializable;
public class CritterClass implements Serializable
{
// What is transient?
private static final long serialVersionUID = -7704164558093534885L;
private String _name;
private String _area;
private int _minRank;
private int _capRank;
private int _box;
private int _skin;
private int _biped;
private float _avgLoot;

public CritterClass(String name, String area, int minRank, int
capRank,
int box, int skin, int biped, float avgLoot)
{
_name = name ;
_area = area ;
_minRank = minRank;
_capRank = capRank;
_box = box;
_skin = skin;
_biped = biped;
_avgLoot = avgLoot;
}
public CritterClass() {
/*
_name = "";
_area = "";
_minRank = 0;
_capRank = 0;
_box = 0;
_skin = 0;
_biped = 0;
_avgLoot = 0;
*/
}



public String toString()
{
String result = " " + _name + " " + _area + "\t" + _minRank + "
" + _capRank + " " + _box + " " + _skin + " "
+ _biped + "\t" + _avgLoot + "\n";
return result ;
}
}
 
S

Sudsy

Rich Wahl wrote:
I have this snippet of code running when I click a View button, I want
the code to read in the Objects from a File and then output them into
a TextField on the Frame. The Code is Syntaxically correct, But when
it gets to the
"outputField.append(tempCritter.toString());" line.
It throws a null pointer exception. But The tempCritter cant be null
if it gets to that line.
<snip>

No, but outputField could be.
 
P

Paul Lutus

Rich said:
So I threw out my Idea about using JDBC, and went to Serialization of
a Class and using just a File/Object reader/writer.

I have this snippet of code running when I click a View button, I want
the code to read in the Objects from a File and then output them into
a TextField on the Frame. The Code is Syntaxically correct, But when
it gets to the
"outputField.append(tempCritter.toString());" line.
It throws a null pointer exception. But The tempCritter cant be null
if it gets to that line.

Please try to think like a scientist. Rather than saying "It can't be!", why
not test the pointer for null? If you get a null pointer exception, chances
are the pointer is null. Instead of living in denial, find out why it is
null.

/ ...
while((tempCritter = (CritterClass)instream.readObject()) != null) {
outputField.append(tempCritter.toString());

Whoa! Where is outputField declared? You didn't include enough code. Maybe
it is outputField that is null.
 
R

Rich Wahl

Paul Lutus said:
Please try to think like a scientist. Rather than saying "It can't be!", why
not test the pointer for null? If you get a null pointer exception, chances
are the pointer is null. Instead of living in denial, find out why it is
null.

/ ...


Whoa! Where is outputField declared? You didn't include enough code. Maybe
it is outputField that is null.

Yeah, so I was able to figure out through some tests that it is infact
my outputField textarea that is wonky, but how or why it is that way,
Is beyond me. I know there are probably better ways to group/code
this, but its my first re-venture into Java in about a year or two, so
im still brushin up on the forgotten trade niche's.

I have tried to just output a single field to the console, and it does
that, so I know its not a problem with my (de)serialization, Im
confused as to how the textarea is null...

The Code is semi big, but here it is.
__________________________________________



/**
* <p>Title: Critter DB, Java Style</p>
* <p>Description: DR hax hax</p>
* <p>Copyright: Copyright (c) 2004 Rich Wahl</p>
* <p>Company: RichWare</p>
* @version 1.0
*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;
import java.awt.BorderLayout;


public class Critters extends JFrame implements ActionListener,
WindowListener, ItemListener
{
public CritterClass[] critterDB = new CritterClass[500];
private JTextArea outputField;
private JDialog dialog;


Critters frame;
JTextField nameField ;
JTextField areaField ;
JTextField minField ;
JTextField capField ;
JTextField boxField ;
JTextField skinField ;
JTextField bipField ;
JTextField lootField ;
public Critters() {
addWindowListener(this);
// Panel with the Name

Panel namePanel = new Panel();
namePanel.setLayout(new BorderLayout());
Label nameLabel = new Label(" Name Area
MinRanks CapRanks Boxes Skinnable Biped
AverageLoot");
namePanel.add(nameLabel, BorderLayout.NORTH);
JTextArea outputField = new JTextArea(20, 55);
outputField.setEnabled(false);
namePanel.add(outputField, BorderLayout.SOUTH);

// Panel with the Buttons
Panel buttonPanel = new Panel();
buttonPanel.setLayout(new GridLayout(1,3));
JButton addButton = new JButton("Add");
buttonPanel.add(addButton);
addButton.addActionListener(this);
String names[] =
{ "Sort", "Name", "Area", "MinRanks", "CapRanks" , "Boxes",
"Skinnable", "Biped", "AvgLoot" };
JComboBox sortButton = new JComboBox(names);
buttonPanel.add(sortButton);
sortButton.addItemListener(this);
JButton viewButton = new JButton("View");
buttonPanel.add(viewButton);
viewButton.addActionListener(this);



getContentPane().setLayout(new BorderLayout());
getContentPane().add(namePanel, BorderLayout.NORTH);
getContentPane().add(buttonPanel, BorderLayout.SOUTH);
}






public static void main(String[] args) {
Critters frame = new Critters();
frame.setTitle("Button Frame");
frame.pack();
frame.setVisible(true);

}
public void actionPerformed( ActionEvent event ) {
if (event.getActionCommand() == "View") {
try {
ObjectInputStream
instream = new ObjectInputStream( new
FileInputStream("CritterDB.rdb"));
int index = 0;
System.out.println(index);
CritterClass tempCritter = new CritterClass();
tempCritter = (CritterClass)instream.readObject();
//while((tempCritter = (CritterClass)instream.readObject()) !=
null) {
outputField.append(tempCritter.getName());
outputField.append(tempCritter.toString());
// index++;
// System.out.println(index);
// }//close while
instream.close();
} // Try in View

catch (Exception d) {
System.out.println(d.getMessage());
d.printStackTrace();
}
}// View Button

if (event.getActionCommand() == "Add") {
try {
dialog = new JDialog();
JPanel addFrame = new JPanel();

addFrame.setLayout(new GridLayout(2, 8));

Label nameLabel = new Label("Name");
Label areaLabel = new Label("Area");
Label minLabel = new Label("minRank");
Label capLabel = new Label("capRank");
Label boxLabel = new Label("Boxes");
Label skinLabel = new Label("Skinnable");
Label bipLabel = new Label("Biped");
Label lootLabel = new Label("AvgLoot");
addFrame.add(nameLabel);
addFrame.add(areaLabel);
addFrame.add(minLabel);
addFrame.add(capLabel);
addFrame.add(boxLabel);
addFrame.add(skinLabel);
addFrame.add(bipLabel);
addFrame.add(lootLabel);

nameField = new JTextField(10);
areaField = new JTextField(5);
minField = new JTextField(3);
capField = new JTextField(3);
boxField = new JTextField(1);
skinField = new JTextField(1);
bipField = new JTextField(1);
lootField = new JTextField(4);
addFrame.add(nameField);
addFrame.add(areaField);
addFrame.add(minField);
addFrame.add(capField);
addFrame.add(boxField);
addFrame.add(skinField);
addFrame.add(bipField);
addFrame.add(lootField);


JPanel clickers = new JPanel();
JButton addDialogButton = new JButton("AddtoDB");
JButton closeDialog = new JButton("Close");
clickers.add(closeDialog);
clickers.add(addDialogButton);
addDialogButton.addActionListener(this);
closeDialog.addActionListener(this);

dialog.getContentPane().add(addFrame, BorderLayout.NORTH);
dialog.getContentPane().add(clickers, BorderLayout.SOUTH);

dialog.pack();
dialog.show();
}
catch (Exception d) {
System.out.println(d.getMessage());
d.printStackTrace();
}
} // ActionListener for Add (Main Frame)
if(event.getActionCommand() == "Close") {
dialog.dispose();
}
if(event.getActionCommand() == "AddtoDB") {
try {
/*CritterClass critteradd = new CritterClass(nameField.getText(),
areaField.getText(), // Name, Area
Integer.parseInt(minField.getText()),
Integer.parseInt(capField.getText()), // Min Cap
Integer.parseInt(boxField.getText()),
Integer.parseInt(skinField.getText()), // Box, Skin
Integer.parseInt(bipField.getText()),
Integer.parseInt(lootField.getText()) // Stab, Loot
);
*/
CritterClass critteradd = new CritterClass("Goblin", "All", 1, 1,
1, 1, 1, 1);
ObjectOutputStream
outstream = new ObjectOutputStream( new
FileOutputStream("CritterDB.rdb", true));
outstream.writeObject(critteradd);
outstream.close();
nameField.setText("");
areaField.setText("");
minField.setText("");
capField.setText("");
boxField.setText("");
skinField.setText("");
bipField.setText("");
lootField.setText("");
}
catch (Exception d) {
System.out.println(d.getMessage());
d.printStackTrace();
}
} // ActionListener for the AddtoDB button

}
public void windowClosed(WindowEvent event){}

public void windowDeiconified(WindowEvent event){}

public void windowIconified(WindowEvent event){}

public void windowActivated(WindowEvent event){}

public void windowDeactivated(WindowEvent event){}

public void windowOpened(WindowEvent event){}

public void windowClosing(WindowEvent event) {
dispose();
System.exit(0);
}


public void itemStateChanged(ItemEvent event){}

} // Class Ender

============================

Thanks for any advice. (I copy/pasted the Code to make/add the
textarea from my old code, which worked fine, and thats the reason it
never crossed my mind that it would be that aspect that turns out to
be wonky.)
 
S

Sudsy

Rich Wahl wrote:
private JTextArea outputField;

Here, it's an instance variable.

JTextArea outputField = new JTextArea(20, 55);

Here, it's a method variable which "hides" the outer definition.

<snip>

Solution: change the second snippet to remove the type declaration,
i.e.:
outputField = new JTextArea( 20, 55 );

Don't worry, it will gel for you in time.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top