NullPointer Runtime error on clicking New Crime


#1

I’m getting the following runtime errors on clicking the New Crime button added in listings 13.10-13.12. The error references the following line in CrimeFragment.java:

I confirmed that this is the same as the source code for Chapter 13. On a hunch, I changed it to:

This resolved the error and things seem to be working as expected now, but I don’t understand why I’m getting this error with the book/source version. Is there somewhere else in the code that a new crime is defined as having a default setChecked value of false that I’m missing?

11-18 12:15:45.295 9630-9630/com.rahobbs.criminalintent E/AndroidRuntime: FATAL EXCEPTION: main
11-18 12:15:45.295 9630-9630/com.rahobbs.criminalintent E/AndroidRuntime: Process: com.rahobbs.criminalintent, PID: 9630
11-18 12:15:45.295 9630-9630/com.rahobbs.criminalintent E/AndroidRuntime: java.lang.NullPointerException: Attempt to invoke virtual method ‘boolean java.lang.Boolean.booleanValue()’ on a null object reference
11-18 12:15:45.295 9630-9630/com.rahobbs.criminalintent E/AndroidRuntime: at com.rahobbs.criminalintent.CrimeFragment.onCreateView(CrimeFragment.java:86)


#2

Adding to the previous information, the “solution” only works if I check the “solved” box when creating the new crime. Else the app crashes when navigating back to the list. So I know that isn’t actually correct, but hoped the info would help in narrowing down the issue.


Listing 13.9 Goodbye Random Crimes
#3

Take a look at your Crime.java class. This is what’s in the book:

public class Crime {

    ...

    private boolean mSolved;

    ...

    public boolean isSolved() {
        return mSolved;
    }

}

Looking at the error “Attempt to invoke virtual method ‘boolean java.lang.Boolean.booleanValue()’ on a null object reference”. It looks like there’s a null Boolean object in mCrime.isSolved(). The setChecked method takes in a boolean (lower-case b). If you pass in the object type (Boolean, upper-case b), java will automatically convert it to the primitive. If your Boolean is null (which it is by default), you’ll get a null pointer exception here.

I’m guessing that the mSolved boolean in Crime.java is a Boolean (which defaults to null) rather than a boolean (which defaults to false).

Does that fix the problem?


NullPointerException When I clicked Add newCrime item
#4

It does! Thanks so much. I definitely did not see my erroneous capital B when looking over everything many, many times.


#8

I had been scratching my head for ages on this. A very clear explanation. Thank you cstewart!