Don't Be negative
Don't Be negative

Reputation: 1215

Error: NullPointerException when starting activity on devices without NFC

I have created an application for NFC phones. The app should start one activity if the device supports NFC and another if it does not.

So on start up I have done with this to filter NFC vs. non-NFC phones:

mNfc = NfcAdapter.getDefaultAdapter(this);
if (mNfc == null | !mNfc.isEnabled()) {
    Intent a = new Intent(AA.this, AB.class);
    a.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
    startActivity(a);
} else {
    Intent b = new Intent(AA.this, BB.class);
    b.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
    startActivity(b);
}

This works fine with NFC phones (even when NFC is disabled). However, on non-NFC phones this leads to the following exception:

java.lang.RuntimeException: Unable to start activity ComponentInfo{MainActivity}: java.lang.NullPointerException

For testing purposes, I have done this on non-NFC phones

if (mNfc == null) {
    Toast.makeText(this, "This device doesn't support NFC.", Toast.LENGTH_LONG).show();     
}

This works without any exception and I see the toast message.

Upvotes: 1

Views: 110

Answers (1)

Michael Roland
Michael Roland

Reputation: 40851

The problem is that you are using a bitwise OR operator (|) in the expression

if (mNfc == null | !mNfc.isEnabled()) {

This causes both mNfc == null and !mNfc.isEnabled() to be evaluated. As a result, you call isEnabled() on a null object reference (mNfc).

When you change the expression to use a logical OR operator (||)

if (mNfc == null || !mNfc.isEnabled()) {

then the expression mNfc == null will be evaluated first, and as it evaluates to true (which implies that the whole logical expression must evaluate to true), the remaining part of the expression will not be evaluated at all. Hence, mNfc.isEnabled() is not invoked in that case.

Upvotes: 4

Related Questions