I am a junior android developper working on a Nfc Reader project. And I use Mifare Cards. I can only read the UID for the card but unable to read records that I wrote using Nfc Tools with my app but it gives me a null when logging the Ndef value in my console. Any help? Thanks in advance Here's my code
public class MainActivity extends AppCompatActivity {
private TextView mNfcText;
private String mTagText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNfcText = (TextView) findViewById(R.id.textME);
}
@Override
public void onNewIntent(Intent intent) {
super.onNewIntent(intent);
Tag detectedTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
Ndef ndef = Ndef.get(detectedTag);
System.out.println("NDEF >>>"+ndef); //gives null
readNfcTag(intent);
mNfcText.setText(mTagText);
}
/**
* NFC READ
*/
private void readNfcTag(Intent intent) {
if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) {
Parcelable[] rawMsgs = intent.getParcelableArrayExtra(
NfcAdapter.EXTRA_NDEF_MESSAGES);
NdefMessage msgs[] = null;
int contentSize = 0;
if (rawMsgs != null) {
msgs = new NdefMessage[rawMsgs.length];
for (int i = 0; i < rawMsgs.length; i++) {
msgs[i] = (NdefMessage) rawMsgs[i];
contentSize += msgs[i].toByteArray().length;
}
}
try {
if (msgs != null) {
NdefRecord record = msgs[0].getRecords()[0];
String textRecord = parseTextRecord(record);
mTagText += textRecord + "\n\ntext\n" + contentSize + " bytes";
}
} catch (Exception e) {
}
}
}
/**
* PArser
*/
public static String parseTextRecord(NdefRecord ndefRecord) {
if (ndefRecord.getTnf() != NdefRecord.TNF_WELL_KNOWN) {
return null;
}
if (!Arrays.equals(ndefRecord.getType(), NdefRecord.RTD_TEXT)) {
return null;
}
try {
byte[] payload = ndefRecord.getPayload();
String textEncoding = ((payload[0] & 0x80) == 0) ? "UTF-8" : "UTF-16";
int languageCodeLength = payload[0] & 0x3f;
String languageCode = new String(payload, 1, languageCodeLength, "US-ASCII");
String textRecord = new String(payload, languageCodeLength + 1,
payload.length - languageCodeLength - 1, textEncoding);
System.out.println("Text "+textRecord);
return textRecord;
} catch (Exception e) {
throw new IllegalArgumentException();
}
}