I am trying to publish and subscribe data to MQTT using below my code,
try{
ObjectMapper mapper = new ObjectMapper();
MqttMessage message2 = new MqttMessage();
MQTT mqtt_connect = new MQTT();
mqtt_connect.setHost(Host_Address, Integer.parseInt(port));
String topic = "/call/publishcall";
mqtt_connect.setClientId("publishcall");
mqtt_connect.setWillRetain(false);
mqtt_connect.isWillRetain();
mqtt_connect.setWillTopic(topic);
BlockingConnection m_publisher = mqtt_connect.blockingConnection();
m_publisher.connect();
if(m_publisher.isConnected()){
System.out.println("connected");
message2.setPayload();
Object o2 = message2;
String s2 = o2.toString();
mqtt_connect.setWillMessage(o2.toString());
m_publisher.publish(topic, s2.getBytes(), QoS.AT_MOST_ONCE, false);
Topic [] topics = {new Topic("/call/subscribecall", QoS.AT_MOST_ONCE)};
m_publisher.subscribe(topics);
Message message = m_publisher.receive(20000, TimeUnit.MILLISECONDS);
byte[] payload = message.getPayload();
String messageContent = new String(payload);
System.out.println("Received message from topic: " + message.getTopic() + " Message content: " + messageContent);
message.ack();
if(messageContent =="0"){
//i want to do something based on result 0
}
else if(messageContent =="1"){
//i want to do something based on result 1
}
else
{
//i want to do something based on result except 0 or 1
}
m_publisher.disconnect();
}
else
{
System.out.println("not connected");
}
} catch (Exception e) {
e.printStackTrace();
return "failure";
}
but i can publish data fine to MQTT. when they publishing data with topic name as /call/subscribecall i am getting null pointer exception in that message.getPayload();
but the subscriber sending data correctly.
why i am getting null instead of subscriber sending data? It seems the subscribe code not getting the data.
where am i doing mistake?