0

I am doing an MVC GUI project in Java. I have a 3 Frames and 3 Controllers, 1 for each view. The problem is that I can create Person objects but when I want to get their values from the static ArrayList where are stored sends me an NullPointerException. But the ArrayList isn't empty cause with TestCases I have secured this.

public class ControladorFormulario {
    public static PoolPersonas poolPersonas = new PoolPersonas();
    public static Persona persona = new Persona();

    public static void activarVistaEditar(String dni, Formulario frame) {
        if (dni == null) {
            return;
        }
        frame.getTxtDni().setText(dni);
        frame.getTxtDni().setEnabled(false);
        Persona persona =  poolPersonas.obtenerPersona(dni);
        frame.getTxtNombre().setText(persona.getNombre());


    }
}

And the method that gets the person with the String is the next one:

public Persona obtenerPersona(String dni) {
    Persona personaObtenida = null;
    for (Persona persona : getPoolPersonas()) {
        if (persona.getDni() == dni) {
            personaObtenida = persona;
        }
    }
    return personaObtenida;
}

So, when I press the button that calls the activarVistaEditar function, it returns me somehow a Null value, instead of the person I'm trying to acces.

I have already checked that I've passed a correct String and Frame to the function, and the values are the correct ones. I just don't understand why I can't acces to the persons in the poolPersonas Object in this place and I can do it in another places.

Baltimer
  • 31
  • 1
  • 5
  • 1
    Possible duplicate of [How do I compare strings in Java?](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – Zircon Apr 03 '17 at 19:15
  • It looks like you might have never added any Personas to the PoolPersonas - PoolPersonas is empty. In this case obtenerPersonas would return null (assuming PoolPersonas is not null). – HedonicHedgehog Apr 03 '17 at 19:17
  • Try replacing `if (persona.getDni() == dni) {` with `if (persona.getDni().equals(dni)) {` – Darshan Mehta Apr 03 '17 at 19:18
  • It was a problem with the comparasion, thank you to all :) – Baltimer Apr 04 '17 at 14:11

1 Answers1

0

yes like Zircon says, or means: You compare strings with equals() not ==

if (persona.getDni().equals(dni)) 

Since you are comparing object references instead of their values the if statement will always evaluate to false.

Jack Flamp
  • 1,223
  • 1
  • 16
  • 32