androidkotlinmqttnoclassdeffounderror

NoClassDefFoundError -> How can I make this kotlin code work to implement a MQTT connection?


I found this code on this site, it implements an MQTT client for Android, and it's written in Kotlin.

I have really few experience with this language, so I don't understand how to make it work. I copied it into my MainActivity.kt file and I'm calling connect(this) from onCreate function:

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        setSupportActionBar(findViewById(R.id.toolbar))
        connect(this)
        ...

This is the connect function:

    private fun connect(context: Context){


        var serverURI = "tcp://broker.hivemq.com:1883"
        mqttClient = MqttAndroidClient(context, serverURI, "SmartFarmerApp")
        mqttClient.setCallback(object: MqttCallback{
            override fun messageArrived(topic: String?, message: MqttMessage?) {
                Log.d(TAG, "Receive message: ${message.toString()} from topic: $topic")
            }

            override fun connectionLost(cause: Throwable?) {
                Log.d(TAG, "Connection lost ${cause.toString()}")
            }

            override fun deliveryComplete(token: IMqttDeliveryToken?) {
                TODO("Not yet implemented")
            }
        })

        val options = MqttConnectOptions()
        try {
            mqttClient.connect(options, null , object: IMqttActionListener {
                override fun onSuccess(asyncActionToken: IMqttToken?) {
                    Log.d(TAG, "Connection success")
                }

                override fun onFailure(asyncActionToken: IMqttToken?, exception: Throwable?) {
                    Log.d(TAG, "Connection failure")
                }
            })
        }catch( e: MqttException){
            e.printStackTrace()
        }
    }

The first line inside the try block gives me an error: java.lang.NoClassDefFoundError: Failed resolution of: Landroidx/localbroadcastmanager/content/LocalBroadcastManager;

What could I do?


Solution

  • I solved it adding a line into build.gradle (module). I added this one:

    implementation 'com.android.support:support-v4:30.x.x'
    

    that number 30 is my compileSdkVersion, that I found in the same file