I am trying to read an NFC tag using Android. I'm a beekeeper and this is to ID my hives when I approach them. I have searched here but I am still having issues reading the tag. I want to read the text, but when it reads, there is a square-like character and characters displayed like " Ten" before the desired text.
Here is the code I'm using. I know that the payload bytes have to be correct and I have tried changing them but to no avail.
private static NdefMessage getTestMessage() {
byte[] mimeBytes = "application/com.android.cts.verifier.nfc"
.getBytes(Charset.forName("US-ASCII"));
byte[] id = new byte[] {1, 3, 3, 7};
byte[] payload = "CTS Verifier NDEF Push Tag".getBytes(Charset.forName("US-ASCII"));
return new NdefMessage(new NdefRecord[] {
new NdefRecord(NdefRecord.TNF_MIME_MEDIA, mimeBytes, id, payload)
});
}
@Override
protected void onResume() {
super.onResume();
mNfcAdapter.enableForegroundDispatch(this, mPendingIntent, null, null);
mNfcAdapter.setNdefPushMessageCallback(this, this);
}
// sending message
@Override
public NdefMessage createNdefMessage(NfcEvent event) {
return getTestMessage();
}
private NdefMessage[] getNdefMessages(Intent intent) {
Parcelable[] rawMessages = intent
.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
if (rawMessages != null) {
NdefMessage[] messages = new NdefMessage[rawMessages.length];
for (int i = 0; i < messages.length; i++) {
messages[i] = (NdefMessage) rawMessages[i];
}
return messages;
} else {
return null;
}
}
static String displayByteArray(byte[] bytes) {
String res="";
StringBuilder builder = new StringBuilder().append("");
for (int i = 0; i < bytes.length; i++) {
res+=(char)bytes[i];
}
return res;
}
// displaying message
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
NdefMessage[] messages = getNdefMessages(intent);
edtUser.setText(displayByteArray(messages[0].toByteArray()));
Toast.makeText(this, "NFC tag entered", Toast.LENGTH_LONG).show();
}