Search code examples
androidkotlinnfc

Android, Kotlin: Checking if an NdefMessage converted to a String is equal to another String


I am trying to check if a value read from an NFC tag is equal to a String. The value written in the tag is correctly extracted, but when I try to compare the value with another string, as in the second "if" statement, it will always enter the "else" block.

private fun processNdefMessages(ndefMessages: Array<NdefMessage?>) {
        var msg =  ""
        for (curMsg in ndefMessages) {
            if (curMsg != null) {
                // get the text written in the tag
                msg = String(curMsg.getRecords().get(0).getPayload())
            }
        }
        textFromTag = msg
        if (textFromTag.equals("enjacket1")) {
            Toast.makeText(applicationContext, "jacket1", Toast.LENGTH_LONG).show()
        } else {
            Toast.makeText(applicationContext, "$textFromTag", Toast.LENGTH_LONG).show()
        }

EDIT: Also, when I read the payload from the tag, it always starts with "en" and then the actual string. This is why I compare the textFromTag with "enjacket1". I tried to eliminate the first two charaacters, but nothing seems to make a change to it...


Solution

  • This is probably because there is an extra byte in front of the language en characters to specify the language length which is probably not printable.

    As NFC text is encoded as:

    • language length (1 byte) + language (n bytes) + Text

    So read the first byte and trim accordingly or quick hack trim the first 3 bytes off for english messages.

    More details at https://stackoverflow.com/a/59515909/2373819