alextoombs
alextoombs

Reputation: 33

FormatException when Creating NdefMessage

I mistook my original question as one of conversion, when it's one of a FormatException. I'm trying to write an NFC tag based upon an EditText input. Relevant code below:

EditText msgInput = (EditText) findViewById(R.id.editText1);

...

try {
    String msg = msgInput.getText().toString();
    byte[] bytes = msg.getBytes();
    messagePayload = bytes;
}

...

NdefMessage message;
try {
message = new NdefMessage(messagePayload);
} catch (FormatException e) {
// ups, illegal ndef message payload
Log.e(TAG, "Format exception from illegal ndef message payload");

return;
}

And it's always throwing that FormatException. I'm not sure why. I'm just trying to write 'xyz' or 'stuff' or something like that. I ensure I'm getting the right bytes from Log statements between each.

Upvotes: 0

Views: 1503

Answers (1)

Kamen Goranchev
Kamen Goranchev

Reputation: 1906

Giving just the bytes of an string is not a valid NdefMessage payload. That is why you get an exception. To construct the correct NdefMessage with one text record that is formatted according to NFC Forum standard use this code:

            String msg = msgInput.getText().toString();
    byte[] languageCode;
    byte[] msgBytes;
    try {
        languageCode = "en".getBytes("US-ASCII");
        msgBytes = msg.getBytes("UTF-8");
    } catch (UnsupportedEncodingException e) {
        return;
    }

    byte[] messagePayload = new byte[1 + languageCode.length
            + msgBytes.length];
    messagePayload[0] = (byte) 0x02; // status byte: UTF-8 encoding and
                                        // length of language code is 2
    System.arraycopy(languageCode, 0, messagePayload, 1,
            languageCode.length);
    System.arraycopy(msgBytes, 0, messagePayload, 1 + languageCode.length,
            msgBytes.length);

    NdefMessage message;
    NdefRecord[] records = new NdefRecord[1];
    NdefRecord textRecord = new NdefRecord(NdefRecord.TNF_WELL_KNOWN,
            NdefRecord.RTD_TEXT, new byte[]{}, messagePayload);
    records[0] = textRecord;
    message = new NdefMessage(records);

For more detail on the NDEF protocol please refer to this document: https://engineering.purdue.edu/477grp14/Specs/NFC/NDEFTECH.pdf

For more details on the text RTD look at this one: http://www.maintag.fr/fichiers/pdf-fr/nfcforum-ts-rtd-text-1-0.pdf

Upvotes: 2

Related Questions