0

These are my classes.

public class Prova {
    private static HashMap<String,UtenteAstratto> map = new HashMap<String,UtenteAstratto>();
    public static void main(String[] args) {
        DatiPersonali dp1 = new DatiPersonali("a", "a", "a", "a", "a", "a", "a", "a");
        UtenteRegistrato u1 = new UtenteRegistrato(dp1);
        map.put(u1.getUsername(), u1);

        DatiPersonali dp2 = new DatiPersonali("b", "b", "b", "b", "b", "b", "b", "b");
        UtenteRegistrato u2 = new UtenteRegistrato(dp2);
        AdminDecorator ad = new AdminDecorator(u2);
        map.put(ad.getUsername(), ad);


        DatiPersonali dp3 = new DatiPersonali("c", "c", "c", "c", "c", "c", "c", "c");
        UtenteRegistrato u3 = new UtenteRegistrato(dp3);
        GestoreDecorator gd = new GestoreDecorator(u3);
        map.put(gd.getUsername(), gd);

        System.out.println(map.toString());
        System.out.println();
        save(map);
        load();
    }

    private static void load() {
        try {
            String nomeFile = "fileProva.sav";
            FileInputStream fis = new FileInputStream(nomeFile);
            ObjectInputStream ois = new ObjectInputStream( fis );
            Object o = ois.readObject();
            if( !o.equals("") ) {
                map = (HashMap<String,UtenteAstratto>) o;
                for(Entry elem: map.entrySet()) {
                    System.out.println("username= " + elem.getKey() + " " + elem.getValue());
                }
            }
            ois.close();
            fis.close();        
        }catch( Exception e ) {
            e.printStackTrace();
        }

    }

    public static void save(Object o) {
        try {
            FileOutputStream fos = new FileOutputStream("fileProva.sav");
            ObjectOutputStream oos = new ObjectOutputStream( fos );
            oos.writeObject(o);
            oos.close();
            fos.close();            
        }catch(Exception e) {
            e.printStackTrace();
        }
    }


}

With this error.

java.lang.NullPointerException
    at Utilities_Utente.UtenteDecorator.toString(UtenteDecorator.java:9)
    at java.base/java.lang.String.valueOf(String.java:3352)
    at java.base/java.lang.StringBuilder.append(StringBuilder.java:166)
    at Utilities_Utente.Prova.load(Prova.java:43)
    at Utilities_Utente.Prova.main(Prova.java:31)

Class GestoreDecorator

public class GestoreDecorator extends UtenteDecorator implements Serializable{

    private static final long serialVersionUID = 8246098147192933576L;

    public GestoreDecorator (UtenteAstratto u){
        DatiPersonali dp =new DatiPersonali(u.getDatiPersonali());

        utente = new UtenteRegistrato(dp);
        utente.setPermesso(Permesso.GESTORE);
    }

    public void setPermesso(){
    }


}

Class AdminDecorator

public class AdminDecorator extends UtenteDecorator implements Serializable{
    private static final long serialVersionUID = -8816003037658470920L;

    public AdminDecorator (UtenteAstratto u){
        DatiPersonali dp = new DatiPersonali(u.getDatiPersonali());

        utente = new UtenteRegistrato(dp);
//      utente = (UtenteRegistrato) u;
        utente.setPermesso(Permesso.ADMIN);
    }


    @Override
    public void setPermesso() {
        // TODO Auto-generated method stub

    }


}

Class UtenteAstratto

public abstract class UtenteAstratto implements Comparable<UtenteAstratto>{
    public enum Permesso { UTENTE, ADMIN, GESTORE };

    public abstract String getUsername();//questo metodo serve nella classe Squadra.Squadra
    public abstract String getPassword();//questo metodo serve nella classe Squadra.Squadra
    public abstract DatiPersonali getDatiPersonali();//questo metodo serve nella classe Squadra.Squadra
    public abstract Permesso getPermesso();

}

Class UtenteDecorator

public abstract class UtenteDecorator extends UtenteAstratto {
    protected UtenteRegistrato utente; 

    public abstract void setPermesso();

    public String toString(){
        return utente.toString();
    }

    public int compareTo(UtenteAstratto o) {
        return utente.compareTo(o);
    }

    public String getUsername() {
        return utente.getUsername();
    }

    public String getPassword() {
        return utente.getPassword();
    }

    public DatiPersonali getDatiPersonali() {
        return utente.getDatiPersonali();
    }

    public Permesso getPermesso(){
        return utente.getPermesso();
    }

}

Class UtenteRegistrato

public class UtenteRegistrato extends UtenteAstratto implements Serializable{
    private static final long serialVersionUID = -2593162236417203422L;
    private DatiPersonali dp;

    private Permesso permesso;

    public UtenteRegistrato (DatiPersonali d) {
        this.dp = d;
        permesso = Permesso.UTENTE;
    }//Costruttore

    public Permesso getPermesso(){
        return permesso;
        //return
    }

    public void setPermesso(Permesso p) {
        permesso = p;
    }

    public DatiPersonali getDatiPersonali (){
        return dp;
    }

    public int hashCode() {
        int parziale = super.hashCode();
        final int primo = 41;
        int result = parziale + primo * dp.hashCode() ;
        return result;
    }

    public boolean equals(Object o) {
        if (!(o instanceof UtenteRegistrato))
            return false;
        if (this == o)
            return true;
        UtenteRegistrato user = (UtenteRegistrato) o;
        if (!getUsername().equals(user.getUsername()))
            return false;
        return true;
    }//equals

    public String toString() {
        StringBuilder sb = new StringBuilder (500);
        sb.append(permesso.toString() + " ");
        sb.append(getDatiPersonali().toString());
        return sb.toString();
    }

    public int compareTo(UtenteAstratto o) {
        UtenteAstratto u = null;

        if (o instanceof UtenteDecorator)
            u= (UtenteDecorator) o;
        else
            u= (UtenteRegistrato) o;

        if (getUsername().compareTo(u.getUsername())==0)
            return 0;
        if (dp.getCognome().compareTo(u.getDatiPersonali().getCognome()) <0)
            return -1;
        if (dp.getCognome().compareTo(u.getDatiPersonali().getCognome()) ==0 && dp.getNome().compareTo(u.getDatiPersonali().getNome()) <0)
            return -1;
        return 1;
    }

    @Override
    public String getUsername() {
        return dp.getUsername();
    }

    @Override
    public String getPassword() {
        return dp.getPassword();
    }
}

And the views of debugger.

The view save. enter image description here

The view load. enter image description here

Now, my question is: Why when I load the Hashmap the value 1 and 2 (AdminDecorator and GestoreDecorator) are null?

1 Answers1

3

You should read What is a NullPointerException, and how do I fix it?.

In particular, the stack trace is telling you which line of code is the problem:

java.lang.NullPointerException
    at Utilities_Utente.UtenteDecorator.toString(UtenteDecorator.java:9)

The error occurred in UtenteDecorator.toString at line 9.

There is only one line of code in that toString method:

return utente.toString();

The only possible cause of a NullPointerException in that line of code is that utente is null.

The best thing you can do is force that field to never be null, by adding a constructor:

protected UtenteDecorator(UtenteRegistrato utente) {
    this.utente = Objects.requireNonNull(utente,
        "utente cannot be null.");
}

(Objects is the java.util.Objects class.)

If you don’t want to change the constructor, an alternative is to defensively code your toString method, so it won’t break when utente is null:

public String toString() {
    return Objects.toString(utente, "(utente not defined)");
}
VGR
  • 40,506
  • 4
  • 48
  • 63
  • In this project I cannot accept null because the "user" object contains registration data. The hashmap contains "user.username" as a key and "user" as a value. I would like to know why before writing to the file the "user" object is not null and after writing the "user" object is null in the hashmap (when it is restored). – Anduril92 Apr 21 '20 at 19:44
  • It appears both of the subclasses of `UtenteDecorator` that you’ve shown us are setting `utente` to a non-null value, so I would print `elem.getValue().getClass()` in the `load` method, to determine what subclass is allowing a null value for utente. – VGR Apr 21 '20 at 20:40
  • `class Utilities_Utente.UtenteRegistrato username= a UTENTE DatiPersonali [nome: a, cognome: a, città: a, dataNascita: a, email: a, username: a, nickname: a, password: a] class Utilities_Utente.AdminDecorator java.lang.NullPointerException at Utilities_Utente.UtenteDecorator.toString(UtenteDecorator.java:11) at java.base/java.lang.String.valueOf(String.java:3352) at java.base/java.lang.StringBuilder.append(StringBuilder.java:166) at Utilities_Utente.Prova.load(Prova.java:42) at Utilities_Utente.Prova.main(Prova.java:29)` – Anduril92 Apr 21 '20 at 21:26
  • From what I understand it lost the reference to the object after deserialization. – Anduril92 Apr 21 '20 at 21:44
  • I solved the problem It was enough to implement it in the superclass "UserAbstracted" the class Serializable. Thanks at all for the answers! – Anduril92 Apr 21 '20 at 22:03