Skip to content Skip to sidebar Skip to footer

Android Nullpointerexception - Debugging A Specific Line

If I have a line like this: var.getSomething().getSomethingElse().setNewValue(stuff.getValue().getWhatever()); If that line creates a NullPointerException, is there any way of fin

Solution 1:

You might want to put every part into "Watches":

enter image description here

But I'm pretty sure that both Eclipse and Android Studio would let you inspect the content by just a selection of the part you' re interested in (if you are in debug mode)

Solution 2:

The best I can advice for you is to use @Nullable and @NonNull annotations for all methods with return values. It would not help you to get line where null pointer is but would help to prevent such situations in future.

So if method may return null and you have it in call sequence you will get warning from Android Studio about this. In this case it is better to break sequence and check for null.

For example:

privatestaticclassSeq {

    privatefinalRandomrand=newRandom();

    @NonNullpublic Seq nonNull() {
        returnnewSeq();
    }

    @Nullablepublic Seq nullable() {
        return rand.nextInt() % 100 > 50 ? newSeq() : null;
    }

}

If you write new Seq().nonNull().nonNull().nullable().nonNull(); you will get warning from IDE:

Method invocation `new Seq().nonNull().nonNull().nullable().nonNull()` may produce 'java.lang.NullPointerException'

The best solution in this case is to change code like so:

    Seq seq = new Seq().nonNull().nonNull().nullable();
    if (seq != null) {
        seq.nonNull();
    }

Don't forget to add it into Gradle build script

compile'com.android.support:support-annotations:22.+'

Solution 3:

I am not positive on the way you are doing it. This makes your code tightly coupled and not unit testable.

var.getSomething().getSomethingElse().setNewValue(stuff.getValue().getWhatever());

Instead do something like

var.getSomething();

that get something internally does whatever you are doing as a part of

getSomethingElse().setNewValue(stuff.getValue().getWhatever())

In the same way getSomethingElse() should perform whatever you are doing as a part of

setNewValue(stuff.getValue().getWhatever())

Post a Comment for "Android Nullpointerexception - Debugging A Specific Line"