I have some code I forked off of a website but I could not figure out how to fix this error: "Unresolved Reference: setCallback"
Below is my code:
fun MqttHelper(context: Context) {
mqttAndroidClient = MqttAndroidClient(context, serverUri, clientId)
mqttAndroidClient?.setCallback(object : MqttCallbackExtended {
override fun connectComplete(b: Boolean, s: String) {
Log.w("mqtt", s)
}
override fun connectionLost(throwable: Throwable) {
}
@Throws(Exception::class)
override fun messageArrived(topic: String, mqttMessage: MqttMessage) {
Log.w("Mqtt", mqttMessage.toString())
}
override fun deliveryComplete(iMqttDeliveryToken: IMqttDeliveryToken) {
}
})
connect()
}
fun setCallback(callback: MqttCallbackExtended) {
mqttAndroidClient.setCallback(callback)
}
//in onCreate()
//This one has the error
mqttHelper.setCallback(object : MqttCallbackExtended {
override fun connectComplete(b: Boolean, s: String) {
}
override fun connectionLost(throwable: Throwable) {
}
@Throws(Exception::class)
override fun messageArrived(topic: String, mqttMessage: MqttMessage) {
Log.w("Debug", mqttMessage.toString())
dataReceived.setText(mqttMessage.toString())
}
override fun deliveryComplete(iMqttDeliveryToken: IMqttDeliveryToken) {
}
})
If anyone knows how to fix this that would be great, thank you.
You have to create a class, say MqttHelper.kt
, like this:
class MqttHelper(context: Context) {
var mqttAndroidClient: MqttAndroidClient
init {
val serverUri = "serverUri"
val clientId = "client-id"
mqttAndroidClient = MqttAndroidClient(context, serverUri, clientId)
mqttAndroidClient.setCallback(object : MqttCallbackExtended {
override fun connectComplete(b: Boolean, s: String) {
Log.w("mqtt", s)
}
override fun connectionLost(throwable: Throwable) {
}
@Throws(Exception::class)
override fun messageArrived(topic: String, mqttMessage: MqttMessage) {
Log.w("Mqtt", mqttMessage.toString())
}
override fun deliveryComplete(iMqttDeliveryToken: IMqttDeliveryToken) {
}
})
mqttAndroidClient.connect()
}
fun setCallback(callback: MqttCallbackExtended) {
mqttAndroidClient.setCallback(callback)
}
}
and from within your activity use
var mqttHelper = MqttHelper(this)
mqttHelper.setCallback(...)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.