在读取nfc标签时出现此错误?

时间:2019-08-28 08:06:02

标签: android nfc

我正在尝试制作一个读取text/plain类型的标签的应用程序。但是有时它读得很好,有时会给我这个错误:

  

java.lang.NullPointerException:尝试调用虚拟方法   'android.nfc.NdefRecord [] android.nfc.NdefMessage.getRecords()'在   空对象引用

 public class MainActivity extends AppCompatActivity {
private NfcAdapter mNfcAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.activity_main);

    initNFC();
    NFCEnable();
}

public void NFCEnable ()
{
    NfcManager manager = (NfcManager) getSystemService(Context.NFC_SERVICE);
    NfcAdapter adapter = manager.getDefaultAdapter();
    if (adapter != null && adapter.isEnabled()) {
        // adapter exists and is enabled.
    }
    else {
        Toast.makeText(MainActivity.this,"Enable your NFC!",Toast.LENGTH_LONG).show();
    }
}

private void initNFC(){
    mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
}

@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);


        if(tag != null) {
        Ndef ndef = Ndef.get(tag);
        if(ndef!=null)
        {
            readFromNFC(ndef);

        }
        else {
            Toast.makeText(MainActivity.this,"try again!",Toast.LENGTH_LONG).show();
        }

    }
    }
private void readFromNFC(Ndef ndef) {

    try {
        ndef.connect();


            NdefMessage ndefMessage = ndef.getNdefMessage();
            if(ndefMessage.getRecords()[0]!=null &&!ndefMessage.getRecords()[0].getPayload().equals(""))
            {
            String message = new String(ndefMessage.getRecords()[0].getPayload());

            Log.e("ok",message);
            if(message.equals("tech"))
            {
                Intent intent=new Intent(MainActivity.this, Tech_Activation_Activity.class);
                startActivity(intent);
            }
            else   if(message.equals("event"))
            {
                Intent intent=new Intent(MainActivity.this, Event_Executed.class);
                startActivity(intent);
            }
            else {
                Log.e("ok","blank");
            }
          }

        else {
            Toast.makeText(MainActivity.this,"Empty NFC TAG!",Toast.LENGTH_LONG).show();
        }

        ndef.close();
    } catch (IOException | FormatException e) {
        e.printStackTrace();
        Log.e("ok",e.toString());
        if(e.toString().equals("java.io.IOException"))
        {
            Toast.makeText(MainActivity.this,"Get your phone near to NFC!",Toast.LENGTH_LONG).show();
        }


    }
}


@Override
protected void onResume() {
    super.onResume();
    getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
    IntentFilter techDetected = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
    IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
    IntentFilter ndefDetected = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
    ndefDetected.addCategory(Intent.CATEGORY_DEFAULT);
    try {
        ndefDetected.addDataType("text/plain");
    } catch (IntentFilter.MalformedMimeTypeException e) {
        e.printStackTrace();
    }
    IntentFilter[] nfcIntentFilter = new IntentFilter[]{techDetected,tagDetected,ndefDetected};

    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
    if(mNfcAdapter!= null)
        mNfcAdapter.enableForegroundDispatch(this, pendingIntent, nfcIntentFilter, null);

}
@Override
protected void onPause() {
    super.onPause();
    if(mNfcAdapter!= null)
        mNfcAdapter.disableForegroundDispatch(this);
}

请告诉我是否有任何更改或我做错了什么。另外,为了在nfc标签中写入数据,我使用了available在Play商店中的免费应用程序。

2 个答案:

答案 0 :(得分:0)

尝试使用TextUtils.isEmpty()。它同时检查nullempty space。它可以使您的代码更简洁。

if(TextUtils.isEmpty(ndefMessage.getRecords()[0]) && !TextUtils.isEmpty(ndefMessage.getRecords()[0].getPayload())){
    // TODO
}

我不太确定。但是您最好使用try-catch来实现。

答案 1 :(得分:0)

   Ndef ndef = Ndef.get(tag);
        if(ndef!=null)
        {
            readFromNFC(ndef);

        }
        else {
            Toast.makeText(MainActivity.this,"try again!",Toast.LENGTH_LONG).show();
        }