The objective of the readData
method below is to return the NDEF message, whether the tag supports the NDEF format or is "NDEF Formatable".
class WritableTag (tag: Tag) {
private val NDEF = Ndef::class.java.canonicalName
private val NDEF_FORMATABLE = NdefFormatable::class.java.canonicalName
private val ndef: Ndef?
private val ndefFormatable: NdefFormatable?
val tagId: String?
get() {
if (ndef != null) {
return Tools.byteArrayToHex(ndef.tag.id)
} else if (ndefFormatable != null) {
return Tools.byteArrayToHex(ndefFormatable.tag.id)
}
return null
}
init {
val technologies = tag.techList
val tagTechs = Arrays.asList(*technologies)
if (tagTechs.contains(NDEF)) {
Log.i("WritableTag", "contains ndef")
ndef = Ndef.get(tag)
ndefFormatable = null
} else if (tagTechs.contains(NDEF_FORMATABLE)) {
Log.i("WritableTag", "contains ndef_formatable")
ndefFormatable = NdefFormatable.get(tag)
ndef = null
} else {
throw FormatException("Tag doesn't support ndef")
}
}
fun readData(): NdefMessage {
if (ndef != null) {
ndef.connect()
if (ndef.isConnected) {
return ndef.ndefMessage
}
} else if (ndefFormatable != null) {
ndefFormatable.connect()
if (ndefFormatable.isConnected) {
return ndefFormatable.ndefMessage // Unresolved reference: ndefMessage
}
}
throw Exception("Cannot read ndef message")
}
}
I can get the ndefMessage
from the ndef
tag but not from the ndefFormatable
tag. How is this possible?
Because a ndefFormatable
tag is not in the right state to store ndefMessage
s, it needs to be formatted to store ndefMessage
s.
It is not possible to read an ndefMessage
from ndefFormatable
Tag, it is basically a blank card that is indicating that it could store a ndefMessage
if it was setup to store them.
All you can do is format
it and then write
a ndefMessage