[NFC]NFC TAG data reading

on

NFC TAG data reading: There are different type of data can be stored in NFC tag.
Data can be:
TNF = TNF_WELL_KNOWN AND RECORD = RTD_TEXT/RTD_URI
TNF = TNF_ABSOLUTE_URI
TNF = TNF_MIME_MEDIA
TNF = TNF_EXTERNAL_TYPE
Here is android code example where shows how to read the data from tag.

[sourcecode language=”java”]
public void test(Intent intent){
    Parcelable[] data = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
    if (data != null) {
    try {
        for (int i = 0; i < data.length; i++) {
            // array of NDEF messages
            NdefRecord[] recs = ((NdefMessage) data[i]).getRecords();
            for (int j = 0; j < recs.length; j++) {// array of NDEF records
                String text;
                if (recs[j].getTnf() == NdefRecord.TNF_WELL_KNOWN && Arrays.equals(recs[j].getType(),NdefRecord.RTD_TEXT)) {
                    String textEncoding = ((recs[j].getPayload()[0] & 0200) == 0) ? "UTF-8": "UTF-16";
                    int languageCodeLength = recs[j].getPayload()[0] & 0077;
                    text = new String(recs[j].getPayload(),languageCodeLength + 1,recs[j].getPayload().length – languageCodeLength – 1, textEncoding);
                }
                else if ((recs[j].getTnf() == NdefRecord.TNF_ABSOLUTE_URI)) {
                    text = (String) String.format("URI: %1$s\n", new String(recs[j].getType()));
                }
                else if (recs[j].getTnf() == NdefRecord.TNF_MIME_MEDIA) {
                    text = (String) String.format("DATA: %1$s \n", new String(recs[j].getPayload()));
                }
                else if (recs[j].getTnf() == NdefRecord.TNF_WELL_KNOWN && Arrays.equals(recs[j].getType(), NdefRecord.RTD_URI)) {
                    text = (String) String.format("DATA: %1$s \n", new String(recs[j].getPayload()));
                }
                else if ((recs[j].getTnf() == NdefRecord.TNF_EXTERNAL_TYPE)) {
                    text = (String) String.format("DATA: %1$s\n", new String(recs[j].getType()));
                }
            }// for loop for NDEF records finish
        }// for loop for NDEF messages finish
    }
    catch (Exception e) {
        Log.e("TagDispatch", e.toString());
    }
    }
}
[/sourcecode]

Leave a Reply

Your email address will not be published. Required fields are marked *