We have two options for reading the nfc card.
Read from cache
Ndef ndef = Ndef.get(tag); if (ndef == null) { // NDEF is not supported by this Tag. return null; } NdefMessage ndefMessage = ndef.getCachedNdefMessage(); if (ndefMessage == null) { mTextView.setText("The tag is empty !"); return null; } NdefRecord[] records = ndefMessage.getRecords(); for (NdefRecord ndefRecord : records) { if (ndefRecord.getTnf() == NdefRecord.TNF_WELL_KNOWN && Arrays.equals(ndefRecord.getType(), NdefRecord.RTD_TEXT)) { try { return readText(ndefRecord); } catch (UnsupportedEncodingException e) { Log.e(TAG, "Unsupported Encoding", e); } } }
Read directly using
public void readFromTag (intent intent) {
Ndef ndef = Ndef.get(detectedTag); try{ ndef.connect(); txtType.setText(ndef.getType().toString()); txtSize.setText(String.valueOf(ndef.getMaxSize())); txtWrite.setText(ndef.isWritable() ? "True" : "False"); Parcelable[] messages = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES); if (messages != null) { NdefMessage[] ndefMessages = new NdefMessage[messages.length]; for (int i = 0; i < messages.length; i++) { ndefMessages[i] = (NdefMessage) messages[i]; } NdefRecord record = ndefMessages[0].getRecords()[0]; byte[] payload = record.getPayload(); String text = new String(payload); txtRead.setText(text); ndef.close(); } } catch (Exception e) { Toast.makeText(getApplicationContext(), "Cannot Read From Tag.", Toast.LENGTH_LONG).show(); }
}
source share