Domanda

Ho questo metodo, ma in fase di esecuzione che sarà gettato NullPointerException, perché?

il mio metodo:

public static boolean isAddBirth(String name, String family, String fatherName, String mName, String dOfBirth, String pOfBirth) {
    ResultSet rst;
    boolean bool = false;
    Statement stmt;
    try {
        stmt = conn.createStatement();



        rst = stmt.executeQuery("SELECT * FROM birthtable");


        while (rst.next()) {
            if (rst.getString(2).equals(name) && rst.getString(3).equals(family) && rst.getString(4).equals(fatherName) && rst.getString(5).equals(mName) && rst.getString(6).equals(dOfBirth) && rst.getString(7).equals(pOfBirth)) {
                bool = false;
            } else {
                bool = true;
            }
        }
    } catch (SQLException ex) {
        Logger.getLogger(Manager.class.getName()).log(Level.SEVERE, null, ex);
    }
    return bool;




}

stacktrace:

java.lang.NullPointerException
    at database.Manager.isAddBirth(Manager.java:164)
    at AdminGUI.AddNewBornInformation.submit(AddNewBornInformation.java:356)
    at AdminGUI.AddNewBornInformation.setButtonActionPerformed(AddNewBornInformation.java:283)
    at AdminGUI.AddNewBornInformation.access$800(AddNewBornInformation.java:28)
    at AdminGUI.AddNewBornInformation$9.actionPerformed(AddNewBornInformation.java:140)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
    at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
    at java.awt.Component.processMouseEvent(Component.java:6038)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3265)
    at java.awt.Component.processEvent(Component.java:5803)
    at java.awt.Container.processEvent(Container.java:2058)
    at java.awt.Component.dispatchEventImpl(Component.java:4410)
    at java.awt.Container.dispatchEventImpl(Container.java:2116)
    at java.awt.Component.dispatchEvent(Component.java:4240)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4322)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3986)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3916)
    at java.awt.Container.dispatchEventImpl(Container.java:2102)
    at java.awt.Window.dispatchEventImpl(Window.java:2429)
    at java.awt.Component.dispatchEvent(Component.java:4240)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)

anche questi sono nella mia classe:

Logger logger = Logger.getLogger(this.getClass().getName());
private static Connection conn = DBManager.getConnection();
È stato utile?

Soluzione

Dato non ha fornito il numero di riga 164 mi prendo una supposizione che è:

if (rst.getString(2).equals(name) && rst.getString(3).equals(family) && rst.getString(4).equals(fatherName) && rst.getString(5).equals(mName) && rst.getString(6).equals(dOfBirth) && rst.getString(7).equals(pOfBirth)) 

Prima di tutto quella linea mi fa venir voglia di piangere.

Diamo fissarlo:

String a;
String b;
String c;
String d;
String e;
String f;

a = rst.getString(2);
b = rst.getString(3);
c = rst.getString(4);
d = rst.getString(5);
e = rst.getString(6);
f = rst.getString(7);

if (!(a.equals(name))
{
    bool = false;
}

if(!(b.equals(family))
{
    bool = false;
}

if(!(c.equals(fatherName))
{
    bool = false;
}

if(!(d.equals(mName))
{
    bool = false;
}

if(!(e.equals(dOfBirth))
{
    bool = false;
}

if(!(f.equals(pOfBirth))
{
    bool = false;
}

che saranno almeno mostrarvi la linea che ha il puntatore nullo su di esso (supponendo la mia ipotesi è corretta).

Inoltre, a-e sono nomi terribili ... si dovrebbe scegliere quelli meglio di me.

La vera soluzione è quella di utilizzare Object Oriented Programming in cui siano destinate ... facciamo una classe Persona:

public class Person
{
    private final String firstName;
    private final String lastName;
    private final String middleName; // guessing that is what mName is...
    private final String fathersName;
    private final String dateOfBirth;
    private final String placeOfBirth; // guessing that is what pOfBirth is...

    public Person(final String firstName,
                  final String lastName,
                  final String middleName,
                  final String fathersName,
                  final String dateOfBirth,
                  final String placeOfBirth)
    {
        if(firstName == null)
        {
            throw new IllegalArgumentException("firstName cannot be null");
        }

        if(lastName == null)
        {
            throw new IllegalArgumentException("lastName cannot be null");
        }

        ... etc for all of the other arguments ...

        // I would never do the this.fristName thing.. .I would name the parameter different than the instance vairable...
        this.firstName = firstName;
        this.lastName  = lastName;

        ... etc for all of the other arguments ... 
    }

    public boolean equals(final Object o)
    {
        final Person person;

        if(!(o instanceof Person))
        {
            return (false);
        }

        other = (Person)o;

        // the code you I put above + your code for checking if they are equal
    }

    public int hashCode()
    {
        // this is probably good enough
        return (firstName.hashCode() + lastName.hashCode());
    }
}

Poi nel metodo si avrebbe codice di qualcosa di simile a:

rst = stmt.executeQuery("SELECT * FROM birthtable");

    while (rst.next()) 
    {
        final Person person;

        // I would use temp variables rather than passing in the result of getString directly...
        person = new Person(rst.getString(2),
                            rst.getString(3),
                            rst.getString(4),
                            rst.getString(5),
                            rst.getString(6),
                            rst.getString(7));

        // otherPerson would be passed into the method instead of the String you are passing now
        bool = person.equals(otherPerson);

        ... etc ...
    }

Altri suggerimenti

Prima di tutto, anche se stavano lavorando, che il codice non sarebbe fare quello che si voleva che. Non è nemmeno vicino.

In secondo luogo, sarebbe d'aiuto se sapevamo quale linea l'eccezione era su. In luogo di questo, però, siamo in grado di restringere il campo a una delle seguenti opzioni:

  1. conn è nullo.
  2. conn.createStatement(); restituisce null.
  3. stmt.executeQuery() restituisce null.
  4. Una delle rst.getString()s restituisce null.

Sono sicuro che si può capire da lì.

Credo che la causa più probabile è che il metodo "getString" sta tornando nullo.
Le API per questo metodo indica che può restituire null.

String getString (int columnIndex) [...]

Returns: il valore della colonna; se il valore è SQL NULL, il valore restituito è Null

È possibile che questo riferimento API doc è da: ResultSet

Per il vostro programma di essere meno inclini a NullPointerExceptions, si potrebbe assumere che le variabili di input non sono nulli (o assicurare che all'inizio del metodo), e l'arco rovescio della comparazione:

if (name.equals(rst.getString(1)) && ...

L'altra alternativa, che non ho alcun problema con, è quello di utilizzare le ObjectUtils.equals metodo (obj1, obj2) dalla libreria commons-lang, ritorna vero solo se entrambi gli oggetti sono nulli o se obj1 .equals (obj2), ogni altra possibilità torneranno falso. Le classi ObjectUtils e StringUtils hanno un sacco di metodi che sono nulli di sicurezza, vale la pena dare un'occhiata.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top