-1

New to MQTT protocol. My code is working fine on eclipse platform. Now, trying to write publisher mqtt client for android and subscriber is running on eclipse. App is getting closed after launch. Please help me in the following code.

public class MainActivity extends AppCompatActivity 
{
  String text="HELOOO";
  TextView  textReply;
  private MqttClient client;
  public static final String TOPIC = "data";
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    try {
      client = new MqttClient("http://IP-address:1883",     MqttClient.generateClientId());
    } catch (MqttException e) {
      e.printStackTrace();
      System.exit(1);
    }
    try {
      client.connect();

      MqttMessage mssg=new MqttMessage();
      mssg.setPayload(text.getBytes());

      client.disconnect();

    } catch (MqttException e) {
      e.printStackTrace();
      System.exit(1);
    }

  }
}

Changes made after @arjun suggestions

public class MainActivity extends AppCompatActivity {
String text="HELOOO";
TextView  textReply;
private MqttClient client;
public static final String TOPIC = "iot_data";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Publisher myClientTask = new Publisher();
    myClientTask.execute();



}
}
class Publisher  extends AsyncTask<Void, Void, Void>{
String text="helloo";
@Override

protected Void doInBackground(Void... voids) {
    try {
        MqttClient client = new MqttClient("tcp://Ip:1883", MqttClient.generateClientId());
        client.connect();
        MqttMessage mssg=new MqttMessage();
        mssg.setPayload(text.getBytes());
        client.publish("iot_data",mssg);
        client.disconnect();
    }catch(Exception e)
    {


    }


    return null;
}

}

Risha
  • 1
  • 1

1 Answers1

0

Maybe it has to do with that you are not specifying an ip adress properly on the client which leads to an exception where you do a system.exit(1);

  • The IP format is working for eclipse so it must be correct. "tcp:IP_address:1883" – Risha Feb 24 '17 at 09:37
  • yes but "tcp://IP_address:1883" is not a valid address what is IP_address in this case, it should be a address to somewhere. So if you are using a test broker for example the one hivemq has the address should be "tcp://broker.hivemq.com:1883" – Emanuel Mellblom Feb 24 '17 at 09:47
  • Address is valid as i've tested it using already built MQTT clients available on playstore. – Risha Feb 24 '17 at 10:02
  • We can also use IP address of the Mosquitto broker instead. – Risha Feb 24 '17 at 10:02