Search code examples
androidandroid-intentnfcparcelable

Tag tag = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_TAG);


After adding NFC functionality to my app, I have come across a strange error. I have followed many guides and tutorials and they have this line,

Tag tag = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_TAG);

Which does'nt work because Tag needs a Tag but it is receiving a Parcelable object. Im not sure if im missing something or why others seems to work but not mine.

Full method

private void handleIntent(Intent intent)
{
    String action = intent.getAction();
    if(NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action))
    {
        String type = intent.getType();
        if (mime_Text_plain.equals(type))
        {
           Tag tag = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_TAG);
            new NdefReader().execute(tag);
        }
        else
        {
            Log.d(TAG, "Wrong MIME Type!");
        }
    }else if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(action))
    {
        Tag tag = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_TAG);
        String[] nfclist = tag.getTechList();
        String searchedNFC = Ndef.class.getName();

        for (String nfc: nfclist)
        {
            if (searchedNFC.equals(nfc))
            {
                new NdefReader().execute(tag);
                break;
            }
        }
    }
}

Solution

  • You should use Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); instead of Tag tag = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_TAG);

    The first one returns a Tag object and second returns an array.