Error: NullPointerException when starting activity on devices without NFC

Error: NullPointerException when starting activity on devices without NFC

我已经为 NFC 手机创建了一个应用程序。如果设备支持 NFC,则该应用程序应启动一个 activity,如果不支持,则应启动另一个。

所以在启动时我已经完成了这个来过滤 NFC 和非 NFC 手机:

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);
}

这适用于 NFC 手机(即使禁用了 NFC)。但是,在非 NFC 手机上,这会导致以下异常:

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

出于测试目的,我在非 NFC 手机上完成了此操作

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

这毫无例外地工作,我看到了 toast 消息。

问题是您在表达式

中使用了按位或运算符 (|)
if (mNfc == null | !mNfc.isEnabled()) {

这会导致对 mNfc == null!mNfc.isEnabled() 进行评估。因此,您在 null 对象引用 (mNfc) 上调用 isEnabled()

当您更改表达式以使用逻辑或运算符时 (||)

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

那么表达式 mNfc == null 将首先求值,当它求值为 true(这意味着整个逻辑表达式必须求值为 true)时,剩下的部分根本不会评估该表达式。因此,在这种情况下不会调用 mNfc.isEnabled()