Search code examples
javaandroidmqttpahosubscribe

Subscribe to Multiple MQTT topics


I was struggling an issue or maybe it's because of my small background in programming, the issue was about subscribing to multiple topics and showing the subscribed topics in multiple textviews in android

I used to subscribe it like that :

private void setSub()
{
    try{

        client.subscribe(topic,0);

    }
    catch (MqttException e){
        e.printStackTrace();
    }
}

then I've called the setsub() function after the success of the connection to the MQTT client

then I've implemented the setCallBack method and under the messageArrived I've added the line to change the textview value with the message payload I've received from the subscription

@Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
    temp.setText(new String(message.getPayload()));
}

and ofcourse when I define another textview it just took the same result as the first one

so my question is how to configure the MessageArrived function to show each single topic in a single textview?

Thank you in advance.


Solution

  • You can call client.subscribe() as many times as needed with different topics.

    private void setSub()
    {
        try{
    
            client.subscribe(topic1,0);
            client.subscribe(topic2,0);
            client.subscribe(topic3,0);
    
        }
        catch (MqttException e){
            e.printStackTrace();
        }
    }
    

    The messageArrived() callback is passed the topic for each message so you just set up an if statement to decide which textView to update depending on the topic.

    @Override
    public void messageArrived(String topic, MqttMessage message) throws Exception {
      if (topic.equals(topic1) {
        temp.setText(new String(message.getPayload()));
      } else if (topic.equals(topic2) {
        foo.setText(new String(message.getPayload()));
      }
    }
    

    But you should not be calling the setText() method in the callback as it happens on the client thread. You need to look at using runOnUiThread() to do updates.