0

I am trying to identify the unique identifier of NFC tag on android using the following code:

@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 Tag myTag = (Tag) getIntent().getParcelableExtra(NfcAdapter.EXTRA_TAG);
 String nFCID = myTag.getId().toString();   
 Toast.makeText(getApplicationContext(), "NFC id is: "+ nFCID, Toast.LENGTH_SHORT).show();      
}

Unfortunately, when I deploy the app to a real device and scan an NFC tag, my app will crash stating "Unfortunately xyz has to stop...". I know getID() will return byte array and I have to parse it to String. But at least I expect this code to return some values rather than crashing the app. Any ideas how to fix it?

Edited: LogCat outputs:

W/dalvikvm(25548): threadid=1: thread exiting with uncaught exception group=0x41b652a0)
E/AndroidRuntime(25548): FATAL EXCEPTION: main
E/AndroidRuntime(25548): java.lang.RuntimeException: 
Unable to start activity ComponentInfo{com.xyz.nfcid/com.xyz.nfcid.MainActivity}: 
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2100)
Dangila
  • 1,434
  • 3
  • 14
  • 25

1 Answers1

0

I'm pretty sure, that your tag is null. You should check the action String first

String action = intent.getAction();
if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {
    //... do something
}

I've written a complete tutorial, which should help you.

vRallev
  • 4,982
  • 3
  • 31
  • 34