Deserializing an ArrayList. no valid constructor - java

This how I deserialize my arrayList which contains objects of identification
public void deserializeArrayList(){
String path = "./qbank/IdentificationHARD.quiz";
try{
FileInputStream fileIn = new FileInputStream(path);
ObjectInputStream in = new ObjectInputStream(fileIn);
ArrayList<Identification> list = (ArrayList<Identification>) in.readObject();
System.out.println(list);
}catch(Exception e){
e.printStackTrace();
}
}
This is how I serialize it
public void saveItemIdentification(ArrayList<Identification> identification,File file){
try{
ObjectOutputStream out = new ObjectOutputStream(
new FileOutputStream(file));
out.writeObject(identification);
}catch(Exception e){
e.printStackTrace();
}
}
But when I deserialize it it gives me this errors
java.io.InvalidClassException: quizmaker.management.Identification; quizmaker.management.Identification; no valid constructor
at java.io.ObjectStreamClass.checkDeserialize(Unknown Source)
at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at java.util.ArrayList.readObject(Unknown Source)
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 java.io.ObjectStreamClass.invokeReadObject(Unknown Source)
at java.io.ObjectInputStream.readSerialData(Unknown Source)
at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at quizmaker.management.Manage.deserializeArrayList(Manage.java:92)
This is line 92
ArrayList<Identification> list = (ArrayList<Identification>) in.readObject();
Why is this happening?
This is the code of Identification Object.
package quizmaker.management;
import java.io.Serializable;
import quizmaker.Accounts.Rights.IAnswerable;
public class Identification extends Question implements Serializable{
private static final long serialVersionUID = 2L;
private String question;
private String answer;
public Identification(String q , String a){
super(q,a);
}
public String toString(){
return String.format("Question: %s\n Answer %s", getQuestion(),getAnswer());
}
}

Related

How can I serialize a HashMap with BitMatrix objects? (QR Codes / zxing)

I have a "static class" called QRGenerator, whose purpose is to generate BitMatrix objects and to generate BufferedImage objects from them. This is the code for it:
package ericsonwrp.republica.vintage.caixa;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.util.EnumMap;
import java.util.Map;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
public class QRGenerator {
private static BufferedImage image = null;
private static int size = 250;
private static BitMatrix byteMatrix = null;
public static BitMatrix generateBitMatrix(String codeText) {
try {
Map<EncodeHintType, Object> hintMap = new EnumMap<EncodeHintType, Object>(EncodeHintType.class);
hintMap.put(EncodeHintType.CHARACTER_SET, "UTF-8");
hintMap.put(EncodeHintType.MARGIN, 1);
hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
QRCodeWriter qrCodeWriter = new QRCodeWriter();
byteMatrix = qrCodeWriter.encode(codeText, BarcodeFormat.QR_CODE, size,
size, hintMap);
} catch (WriterException e) {
e.printStackTrace();
}
return byteMatrix;
}
public static BufferedImage generateImage(BitMatrix byteMatrix) {
int width = byteMatrix.getWidth();
image = new BufferedImage(width, width,
BufferedImage.TYPE_INT_RGB);
image.createGraphics();
Graphics2D graphics = (Graphics2D) image.getGraphics();
graphics.setColor(Color.WHITE);
graphics.fillRect(0, 0, width, width);
graphics.setColor(Color.BLACK);
for (int i = 0; i < width; i++) {
for (int j = 0; j < width; j++) {
if (byteMatrix.get(i, j)) {
graphics.fillRect(i, j, 1, 1);
}
}
}
return image;
}
}
I have another class called "RepublicaVintageFile", whose purpose is to define an unique file to store the "content" of my application, and to provide a method to serialize (And read, which is irrelevant for the question) this "content". This is the code for it:
package ericsonwrp.republica.vintage.caixa;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.util.HashMap;
public class RepublicaVintageFile {
private HashMap<String, Object> content;
public RepublicaVintageFile() {
setContent(new HashMap<String, Object>());
}
public void serializeContent(String path) throws IOException {
FileOutputStream fout = new FileOutputStream(path, true);
ObjectOutput out = null;
try {
out = new ObjectOutputStream(fout);
out.writeObject(getContent());
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException ex) {
// ignore close exception
}
try {
fout.close();
} catch (IOException ex) {
// ignore close exception
}
}
}
public HashMap<String, Object> getContent() {
return content;
}
public void setContent(HashMap<String, Object> content) {
this.content = content;
}
}
The "content" of my application include BitMatrix objects, which are saved under a label inside a HashMap in a different file (private HashMap<String, BitMatrix> qrItems;). Since serializing the final BufferedImage gives me a java.io.NotSerializableException, I've tried to serialize the BitMatrix objects. But, for my disappointment, that's also impossible. This is the stacktrace:
java.io.NotSerializableException: com.google.zxing.common.BitMatrix
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.writeObject(Unknown Source)
at java.util.HashMap.internalWriteEntries(Unknown Source)
at java.util.HashMap.writeObject(Unknown Source)
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 java.io.ObjectStreamClass.invokeWriteObject(Unknown Source)
at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.writeObject(Unknown Source)
at java.util.HashMap.internalWriteEntries(Unknown Source)
at java.util.HashMap.writeObject(Unknown Source)
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 java.io.ObjectStreamClass.invokeWriteObject(Unknown Source)
at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.writeObject(Unknown Source)
at ericsonwrp.republica.vintage.caixa.RepublicaVintageFile.serializeContent(RepublicaVintageFile.java:26)
at ericsonwrp.republica.vintage.caixa.MainFrame.openSaveAsDialog(MainFrame.java:204)
at ericsonwrp.republica.vintage.caixa.MainFrame.access$1(MainFrame.java:177)
at ericsonwrp.republica.vintage.caixa.MainFrame$4.actionPerformed(MainFrame.java:112)
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$500(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$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.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$JavaSecurityAccessImpl.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)
Considering all this, I come to my question: How can I serialize a HashMap with BitMatrix objects? That's important, because I don't want to store 100 (Or more) separate .png files on a folder and have to read the images all the time in order to get their content.
I've managed to "save" and "load" the BitMatrix objects translating them into boolean 2-dimensional arrays.
private HashMap<String, BitMatrix> qrMatrixes;
private HashMap<String, boolean[][]> qrMatrixBooleanArrays;
As you can see, I have a HashMap of < String, BitMatrix >, with an equivalent in boolean[][] format. That's how I make such "translation" (Transferring the bits from each BitMatrix objects to the boolean[][] arrays):
for (Map.Entry<String, BitMatrix> e : getQrMatrixes().entrySet()) {
boolean[][] b = new boolean[e.getValue().getHeight()][e.getValue().getWidth()];
for (int j = 0; j < e.getValue().getHeight(); j++) {
for (int k = 0; k < e.getValue().getWidth(); k++) {
b[j][k] = e.getValue().get(j, k);
}
}
qrMatrixBooleanArrays.put(e.getKey(), b);
}
Java's Serializer serializes such object (HashMap< String, boolean[][] >) with no problems, no matter how nested it is (I've imagined that it would work with primitive types, with an old-fashioned array). Here's the whole method to update the list with the QR Codes, after loading the file:
public void updateList() {
if (MainFrame.getCurrentFile() != null) {
setQrMatrixes(new HashMap<String, BitMatrix>());
setQrMatrixBooleanArrays(new HashMap<String, boolean[][]>());
for (Map.Entry<String, boolean[][]> e : ((HashMap<String, boolean[][]>) MainFrame.getCurrentFile().getContent().get("Qr Codes")).entrySet()) {
getQrMatrixBooleanArrays().put(e.getKey(), e.getValue());
}
for (Map.Entry<String, boolean[][]> e : getQrMatrixBooleanArrays().entrySet()) {
BitMatrix b = new BitMatrix(e.getValue().length, e.getValue().length);
for (int i = 0; i < e.getValue().length; i++) {
for (int j = 0; j < e.getValue()[i].length; j++) {
if (e.getValue()[i][j] == true) {
b.set(i, j);
}
}
}
getQrMatrixes().put(e.getKey(), b);
qrListModel.addElement(e.getKey());
}
} else {
System.out.println("No file is loaded.");
}
}
I'm afraid it's a bit hard to be more clear. Explore the docs for the BitMatrix object, and just copy the contents into a primitive 2d array. Good luck!

HashMap of HashMap of Generic Type serialization in Java

Fixed, per Engineer Dollery's answer, solution at bottom.
The goal is to serialize the network field of class Network. Sorry for the naming.
I had this, which compiled, and serialized properly.
public class Network {
private HashMap<String, HashMap<String, Number>> network;
...
public void load(String networkFile) throws Exception{
network = (HashMap<String, HashMap<String, Number>>)Utility.deserialize(Utility.load(networkFile));
}
public void save(String networkFile) throws Exception{
Utility.save(networkFile, Utility.serialize(network));
}
}
class Number implements Serializable {
...
}
I changed it to this generic version, which compiles, but no longer serializes. I need someway to specify that HashMap of T and Number is serializable.
public class Network<T extends Serializable> {
private HashMap<T, HashMap<T, Number>> network;
...
public void load(String networkFile) throws Exception{
network = (HashMap<T, HashMap<T, Number>>)Utility.deserialize(Utility.load(networkFile));
}
public void save(String networkFile) throws Exception{
Utility.save(networkFile, Utility.serialize(network));
}
}
class Number implements Serializable {
...
}
And this is the code for serialization
package Bullib;
import java.io.*;
import java.util.*;
import java.util.regex.*;
public class Utility{
public static Pattern phrasePattern = Pattern.compile("[^;:!.?]+");
public static Pattern wordPattern = Pattern.compile("['A-Za-z]+");
public static Object deserialize(byte[] serialized) throws Exception {
ByteArrayInputStream bi = new ByteArrayInputStream(serialized);
ObjectInputStream si = new ObjectInputStream(bi);
return si.readObject();
}
public static byte[] serialize(Object target) throws Exception {
ByteArrayOutputStream bo = new ByteArrayOutputStream();
ObjectOutputStream so = new ObjectOutputStream(bo);
so.writeObject(target);
so.flush();
return bo.toByteArray();
}
public static byte[] load(String filename) throws Exception {
RandomAccessFile file = new RandomAccessFile(new File(filename), "r");
byte[] b = new byte[(int)file.length()];
file.read(b);
file.close();
return b;
}
public static void save(String filename, byte[] value) throws Exception {
RandomAccessFile file = new RandomAccessFile(new File(filename), "rw");
file.write(value);
file.close();
}
public static Collection<String> executeRegex(Pattern pattern, String text){
LinkedList<String> matches = new LinkedList<String>();
Matcher m = pattern.matcher(text);
while (m.find()) {
matches.add(m.group(0));
}
return matches;
}
}
This is the error I get back when trying to serialize with T as either String or Double
Exception in thread "main" java.io.NotSerializableException: Bullib.Network.Netw
ork
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.defaultWriteFields(Unknown Source)
at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.writeObject(Unknown Source)
at java.util.HashMap.writeObject(Unknown Source)
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 java.io.ObjectStreamClass.invokeWriteObject(Unknown Source)
at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.writeObject(Unknown Source)
at java.util.HashMap.writeObject(Unknown Source)
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 java.io.ObjectStreamClass.invokeWriteObject(Unknown Source)
at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.writeObject(Unknown Source)
at Bullib.Utility.serialize(Utility.java:21)
at Bullib.Network.Network.save(Network.java:88)
at Engine.save(Engine.java:63)
at Engine.main(Engine.java:88)
Per requests, an example test and error. As you can see, it produces the same exception as above. I've updated the test to show that it passes if nothing is added to the map, and fails otherwise.
public static void main(String[] args) throws Exception{
Network<String> stringtest = new Network<String>("","","");
stringtest.save("testempty");
stringtest.load("testempty");
System.out.println("passed empty");
stringtest.placeAndMove("fill",0.0);
stringtest.save("testfilled");
stringtest.load("testfilled");
System.out.println("passed filled");
}
java: Bullib/Network/Network
passed empty
Exception in thread "main" java.io.NotSerializableException: Bullib.Network.Netw
ork
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.defaultWriteFields(Unknown Source)
at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.writeObject(Unknown Source)
at java.util.HashMap.writeObject(Unknown Source)
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 java.io.ObjectStreamClass.invokeWriteObject(Unknown Source)
at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.writeObject(Unknown Source)
at java.util.HashMap.writeObject(Unknown Source)
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 java.io.ObjectStreamClass.invokeWriteObject(Unknown Source)
at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.writeObject(Unknown Source)
at Bullib.Utility.serialize(Utility.java:21)
at Bullib.Network.Network.save(Network.java:88)
at Bullib.Network.Network.main(Network.java:108)
The solution is to change
public class Network<T extends Serializable> {
private HashMap<T, HashMap<T, Number>> network;
...
public void load(String networkFile) throws Exception{
network = (HashMap<T, HashMap<T, Number>>)Utility.deserialize(Utility.load(networkFile));
}
public void save(String networkFile) throws Exception{
Utility.save(networkFile, Utility.serialize(network));
}
}
class Number implements Serializable {
...
}
to
public class Network<T extends Serializable> implements Serializable {
private HashMap<T, HashMap<T, Number>> network;
...
public void load(String networkFile) throws Exception{
network = (HashMap<T, HashMap<T, Number>>)Utility.deserialize(Utility.load(networkFile));
}
public void save(String networkFile) throws Exception{
Utility.save(networkFile, Utility.serialize(network));
}
}
class Number implements Serializable {
...
}
Try this:
public class Network implements Serializable

No valid constructor during serialization

I have a major problem during loading the extension into the program. I get an exception as there is no valid constructor.
The problem is in the line:
ekstensja = (ArrayList<Dydaktyk>) ois.readObject();
I get something like that:
java.io.InvalidClassException: Dydaktyk; no valid constructor
at java.io.ObjectStreamClass$ExceptionInfo.newInvalidClassException(Unknown Source)
at java.io.ObjectStreamClass.checkDeserialize(Unknown Source)
at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at java.util.ArrayList.readObject(Unknown Source)
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 java.io.ObjectStreamClass.invokeReadObject(Unknown Source)
at java.io.ObjectInputStream.readSerialData(Unknown Source)
at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at Dydaktyk.wczytajEkstensje(Dydaktyk.java:81)
at Dydaktyk.<clinit>(Dydaktyk.java:69)
at java.io.ObjectStreamClass.hasStaticInitializer(Native Method)
at java.io.ObjectStreamClass.computeDefaultSUID(Unknown Source)
at java.io.ObjectStreamClass.access$100(Unknown Source)
at java.io.ObjectStreamClass$1.run(Unknown Source)
at java.io.ObjectStreamClass$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.io.ObjectStreamClass.getSerialVersionUID(Unknown Source)
at java.io.ObjectStreamClass.initNonProxy(Unknown Source)
at java.io.ObjectInputStream.readNonProxyDesc(Unknown Source)
at java.io.ObjectInputStream.readClassDesc(Unknown Source)
at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.defaultReadFields(Unknown Source)
at java.io.ObjectInputStream.readSerialData(Unknown Source)
at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at java.util.ArrayList.readObject(Unknown Source)
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 java.io.ObjectStreamClass.invokeReadObject(Unknown Source)
at java.io.ObjectInputStream.readSerialData(Unknown Source)
at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.defaultReadFields(Unknown Source)
at java.io.ObjectInputStream.readSerialData(Unknown Source)
at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at java.util.ArrayList.readObject(Unknown Source)
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 java.io.ObjectStreamClass.invokeReadObject(Unknown Source)
at java.io.ObjectInputStream.readSerialData(Unknown Source)
at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at Przedmiot.wczytajEkstensje(Przedmiot.java:99)
at Przedmiot.<clinit>(Przedmiot.java:87)
at GUI.main(GUI.java:100)
static {
wczytajEkstensje(); // load Extension
}
public static void wczytajEkstensje() {// load extension
FileInputStream fis = null;
ObjectInputStream ois = null;
try {
fis = new FileInputStream("dydaktyk.ser");
ois = new ObjectInputStream(fis);
// here is the problem
ekstensja = (ArrayList<Dydaktyk>) ois.readObject();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
try {
if (ois != null) {
ois.close();
}
} catch (IOException e) {
}
try {
if (fis != null) {
fis.close();
}
} catch (IOException e) {
}
}
}
public static void zapiszEkstensje() {// save extension
FileOutputStream fos = null;
ObjectOutputStream oos = null;
try {
fos = new FileOutputStream("dydaktyk.ser");
oos = new ObjectOutputStream(fos);
oos.writeObject(ekstensja); // serialization
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (oos != null) {
oos.close();
}
} catch (IOException e) {
}
try {
if (fos != null) {
fos.close();
}
} catch (IOException e) {
}
}
}
The class Dydaktyk should have an accessible (public or protected) no-args constructor so that the serialization reflection mechanism can create an instance of the class:
public Dydaktyk() {
...
}
From the docs
During deserialization, the fields of non-serializable classes will be initialized using the public or protected no-arg constructor of the class. A no-arg constructor must be accessible to the subclass that is serializable. The fields of serializable subclasses will be restored from the stream.
As specified in Oracle site about Serialization interface :
During deserialization, the fields of non-serializable classes will be
initialized using the public or protected no-arg constructor of the
class. A no-arg constructor must be accessible to the subclass that is
serializable. The fields of serializable subclasses will be restored
from the stream.
What I gues is that Dydaktyk is the subclass of some class. And you have defined the parametric constructor within the superclass and have not defined a parameter-less constructor within it . And the compiler isn't inserting a default constructor for that superclass. So , You should define a parameter-less constructor within your superclass also.

Getting Exception, :- java.lang.NullPointerException?

Getting the following exception:-
java.lang.NullPointerException
at com.local.testing.ChatClient$sendButtonActionListener.actionPerformed(ChatClient.java:53)
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.plaf.basic.BasicButtonListener.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.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForHierarchy(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)
I am using the following two classes:-
package com.local.testing;
import java.net.*;
import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ChatClient {
JTextField outgoing=null;
Socket sock=null;
PrintWriter writer=null;
public void buildGui(){
JFrame frame = new JFrame("ChatClient");
JPanel mainPanel = new JPanel();
outgoing = new JTextField(20);
JButton send = new JButton("send");
send.addActionListener(new sendButtonActionListener());
mainPanel.add(outgoing);
mainPanel.add(send);
frame.getContentPane().add(BorderLayout.CENTER,mainPanel);
frame.setVisible(true);
frame.setSize(400, 400);
frame.pack();
setUpNetworking();
}
private void setUpNetworking(){
try{
sock = new Socket("127.0.0.1",4242);
writer = new PrintWriter(sock.getOutputStream());
System.out.println("Connection Established");
}
catch(UnknownHostException uhe){
uhe.printStackTrace();
}
catch(IOException ioe){
ioe.getMessage();
}
finally{
if(writer !=null){
writer.close();
}
}
}
public class sendButtonActionListener implements ActionListener{
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
//System.out.println(outgoing.getText());
try{
writer.println(outgoing.getText());
writer.flush();
}
catch(Exception e){
e.printStackTrace();
}
outgoing.setText("");
outgoing.requestFocus();
}
}
public static void main(String []x){
ChatClient client = new ChatClient();
client.buildGui();
}
}
package com.local.testing;
import java.io.*;
import java.net.*;
public class ChatServer {
public void connectToClient(){
try {
ServerSocket serverSocket = new ServerSocket(4242);
while(true)
{
Socket sock = serverSocket.accept();
InputStreamReader stream = new InputStreamReader(sock.getInputStream());
BufferedReader reader = new BufferedReader(stream);
String chat=reader.readLine();
System.out.println(chat);
}
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String [] x){
ChatServer server = new ChatServer();
server.connectToClient();
}
}
What could be the issue?
There is something wrong with your setUpNetworking method. If you run the following, you will see that it prints test/test2/null. So you catched the IOException and hence the writer isn't initialized which will throws the NPE :
private void setUpNetworking(){
System.out.println("test");
try{
sock = new Socket("127.0.0.1",4242);
writer = new PrintWriter(sock.getOutputStream());
}
catch(UnknownHostException uhe){
System.out.println("test1");
uhe.printStackTrace();
}
catch(IOException ioe){
System.out.println("test2");
ioe.getMessage();
}
finally{
if(writer !=null){
writer.close();
}
}
System.out.println(writer);
}
If you print the stack trace you get :
java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at com.local.testing.ChatClient.setUpNetworking(ChatClient.java:31)
at com.local.testing.ChatClient.buildGui(ChatClient.java:14)
at com.local.testing.ChatClient.main(ChatClient.java:62)
So you have to fix this error.
It seems that your event handler has be been called before your initialisation in buildGui(). So basically make sure that this function is called earlied e.g. in the constructor.
writer.println(outgoing.getText());
writer is initialized to null and never set to an object before above call.(JTextField outgoing=null;

Run time error when saving and loading planeStore

Hey im getting a run time error when saving and loading my planeStore. The save option saves the store into a text file name of the users choosing and then loads with the user entering the file name.
Here is the error:
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.writeObject(Unknown Source)
at java.util.TreeMap.writeObject(Unknown Source)
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 java.io.ObjectStreamClass.invokeWriteObject(Unknown Source)
at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.writeObject(Unknown Source)
at java.util.HashMap.writeObject(Unknown Source)
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 java.io.ObjectStreamClass.invokeWriteObject(Unknown Source)
at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.defaultWriteFields(Unknown Source)
at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.writeObject(Unknown Source)
at FileUtility.save(FileUtility.java:27)
at MainApp.main(MainApp.java:274)
Fileutility class
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
/**
* <i>Use this class to save and load any type of object (i.e. a container class (e.g. PersonStore), an account, a task, a person)
* #author NMCG
* #version 1.0
*/
public class FileUtility /*serialization - step 2*/
{
/**
* #param fileName relative or absolute file path (e.g. "name.txt" or "c:\\temp\\name.txt"
* #param obj address of any object to be stored (i.e. a container class (e.g. PersonStore), an account, a task, a person)
*/
public static void save(String fileName, Object obj)
{
try
{
FileOutputStream fos = new FileOutputStream(fileName);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(obj);
oos.flush();
oos.close();
fos.close();
}
catch(Exception e)
{
System.out.println("Something bad happened during the save phase!");
e.printStackTrace();
}
}
/**
* #param fileName relative or absolute file path (e.g. "name.txt" or "c:\\temp\\name.txt")
* #return Object address of the object loaded into RAM from file
*/
public static Object load(String fileName) // "test.txt"
{
Object objectIn = null;
try
{
FileInputStream fis = new FileInputStream(fileName);
ObjectInputStream ois = new ObjectInputStream(fis);
objectIn = ois.readObject();
ois.close();
fis.close();
}
catch(Exception e)
{
System.out.println("Something bad happened during the save phase!");
e.printStackTrace();
}
return objectIn;
}
}
Store
case 9:
System.out.println("Store");
int storeChoice;
storeChoice = MenuMethods.getMenuChoice(
"1.Save." +
"\n2.Load.", 2,
"Please enter your choice:", "Error [1,2] Only");
switch (storeChoice)
{
case 1:
System.out.println("Save");
String inputSave;
System.out.println("Please enter the save name:");
inputSave = keyboard.next();
System.out.println("Saving..............");
PlaneStore copyMyStore = airlineMap.copy();
System.out.println(copyMyStore);
//shallow copy would look like this...
PlaneStore shallowCopyMyStore;
//both variables point to same object
shallowCopyMyStore = airlineMap;
//lets store and re-load the mystore object
FileUtility.save(inputSave, airlineMap);
break;
case 2:
System.out.println("Load");
String inputLoad;
System.out.println("Please enter the file name you want to load:");
inputLoad = keyboard.next();
System.out.println("Loading..............");
PlaneStore loadedStore = (PlaneStore)FileUtility.load(inputLoad);
System.out.println("\n--- RELOADED STORE CONTENTS ---");
loadedStore.print();
break;
}
break;
Can anybody see what is wrong?

Categories

Resources