Search code examples
javanullpointerexceptionjava.util.scannerserializabletransient

How do I resolve NullPointerException when I am using Serializable with my classes and transient with Scanner?


I was wondering what things I would need to do to resolve this error. Since making the scanner transient in my class that I want to serialize, I now get a nullpointerexception where the first instance of where the scanner (in) is used.

i.e in.next();

It is the first time I am using Serializable in my work. I have made all my top level classes Serializable.

I was wondering also if anything has to be done to my data structures such as arrays, arraylists etc. What things would need to be tagged as transients?

Any help much appreciated


Solution

  • Values in transient fields are not kept when you serialize an object. One solution is to implement a writeObject method that reinitializes transient fields after an object is deserialized, as described here: http://java.sun.com/developer/technicalArticles/Programming/serialization/

    However, having a Scanner object in a serializable class sounds a bit strange. You should probably split this into two classes - a serializable class that contains the data you want to serialize, and another class that does the user interface or file reading or whatever it is you are doing with a Scanner.