Reputation: 21
I'm writing a URL to an NFC tag (inside a URI record). My problem is that when I read the chip, "%20" is added after "www." and before the remaining part of the URL.
The URL looks like this:
www.%20google.ca
when it should actually look like this:
www.google.ca
The code below is the write function that I use to write the URL to the chip:
String copy = txtTagContent.getText().toString();
byte[] uriField = copy.getBytes(Charset.forName("US-ASCII"));
byte[] payload = new byte[uriField.length + 1]; //add 1 for the URI Prefix
payload[0] = 0x01; //prefixes http://www. to the URI
System.arraycopy(uriField, 0, payload, 1, uriField.length); //appends URI to payload
NdefRecord rtdUriRecord = new NdefRecord(
NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_URI, new byte[0], payload);
NdefMessage message = new NdefMessage(rtdUriRecord);
Ndef ndef = Ndef.get(tag);
ndef.connect();
ndef.writeNdefMessage(message);
ndef.close();
Is there a solution to this problem?
Upvotes: 2
Views: 1843
Reputation: 40841
Neither your method to write the URI record to the NFC tag nor the receiving side would magically add a whitespace (%20) in your URL. Since "http://www." is specified by the prefix byte (0x01
) the whitespace was probably entered into the text field (txtTagContent
). You could simply remove any leading and trailing whitespace using the trim()
method:
String copy = txtTagContent.getText().toString().trim();
You might probably also want to account for URL strings that already contain a certain prefix:
byte prefixByte = (byte)0x01;
if ("http://www.".equals(copy)) {
prefixByte = (byte)0x01;
copy = copy.substr(11);
} else if ("https://www.".equals(copy)) {
prefixByte = (byte)0x02;
copy = copy.substr(12);
} else if ("http://".equals(copy)) {
prefixByte = (byte)0x03;
copy = copy.substr(7);
} else if ("https://".equals(copy)) {
prefixByte = (byte)0x04;
copy = copy.substr(8);
}
Finally, be aware that the URL inside the URI record must be UTF-8 encoded (and not US-ASCII as you currently use):
byte[] uriField = copy.getBytes(Charset.forName("UTF-8"));
byte[] payload = new byte[uriField.length + 1];
payload[0] = prefixByte;
System.arraycopy(uriField, 0, payload, 1, uriField.length);
NdefRecord rtdUriRecord = new NdefRecord(
NdefRecord.TNF_WELL_KNOWN,
NdefRecord.RTD_URI,
new byte[0],
payload);
Upvotes: 2