I am trying to write and read back a number of NdefRecords on Android and am having problems with retrieving the record IDs. I believe it is because they are not being written to the tag initially.
I am creating my record(s) as such:
private NdefRecord createRecord(String text, byte ID) throws UnsupportedEncodingException {
String lang = "en";
byte[] textBytes = text.getBytes();
byte[] langBytes = lang.getBytes("US-ASCII");
int langLength = langBytes.length;
int textLength = textBytes.length;
byte[] id = new byte[1];
id[0] = ID;
int idLength = id.length;
byte[] payload = new byte[1 + langLength + textLength + idLength];
payload[0] = (byte) langLength;
//set use id flag
payload[0] |= (1 << 3);
// copy langbytes and textbytes into payload
System.arraycopy(langBytes, 0, payload, 1, langLength);
System.arraycopy(textBytes, 0, payload, 1 + langLength, textLength);
// System.arraycopy(id, 0, payload, 1 + langLength + textLength, idLength);
NdefRecord recordNFC = new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_TEXT, id, payload);
return recordNFC;
}
public void addRecord(String record_contents, RECORD_IDS record_id) throws UnsupportedEncodingException {
this.records.add(createRecord(record_contents, (byte) record_id.getValue()));
}
I thought I was on to something with the
// System.arraycopy(id, 0, payload, 1 + langLength + textLength, idLength);
But it hasn't worked for me. This method stores NdefRecords in the class object which are then sent using
public void writeStoredRecords(Tag tag) throws IOException, FormatException {
NdefRecord[] final_records = (NdefRecord[]) this.records.toArray(new NdefRecord[0]);
NdefMessage message = new NdefMessage(final_records);
try {
Ndef ndef = Ndef.get(tag);
if (ndef != null) {
ndef.connect();
if(!ndef.isWritable())
return;
ndef.writeNdefMessage(message);
ndef.close();
}
}catch(Exception e){}
}
The record objects have their IDs populated after calling new NdefRecord
but then when reading the tag using the app NXP TagInfo the NDEF record IDs are showing as " ".
Does anyone have any experience with this? As the record IDs are rarely used with NFC the online resources are scarce.
According to the NFC Forum NDEF specification, the ID field of an NDEF record must be a URI. Consequently, NXP TagInfo will treat this value as a URI string and decodes the byte array into a string (I'm not quite sure which encoding they expect though but browsing through the NDEF specification, I would expect US-ASCII encoding).
Since you use a single byte as ID field, that value probably doesn't decode to a printable character. Therefore, NXP TagInfo simply prints " " (quotation marks surrounding the unprintable string value).