0

Hi I am trying to get the message from mqtt broker as a toast, but I keep getting an error for the Toast (red underline in the code), could someone please let me know how to amend this?

here is the code

   import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;



import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

public class MainActivity extends AppCompatActivity implements MqttCallback{
    MqttClient client;
    private String clientInfo = MqttClient.generateClientId();
    //private final MqttMessage message = new MqttMessage();


    public void findSpace(View view) {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //adapted from https://www.eclipse.org/paho/files/javadoc/org/eclipse/paho/client/mqttv3/persist/MemoryPersistence.html
        try {
            MemoryPersistence mp = new MemoryPersistence();
            client = new MqttClient("tcp://10.150.37.228:1883", clientInfo, mp);
            MqttConnectOptions mqttConnectOps = new MqttConnectOptions();
            mqttConnectOps .setCleanSession(true);
            client.connect(mqttConnectOps );
            client.setCallback(this);
            client.subscribe("test");
        } catch (MqttException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void connectionLost(Throwable cause) {

    }

    @Override
    public void messageArrived(String topic, MqttMessage message) throws Exception {
        System.out.println(message);
        CharSequence cs = new String(message.getPayload());
        Toast.makeText(getApplicationContext(), cs, Toast.LENGTH_SHORT).show();

    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken token) {

    }
}
user6248190
  • 1,233
  • 2
  • 16
  • 31
  • Which is the error? What does `message.getPayload()` return? – Héctor May 03 '16 at 13:33
  • @bigdestroyer the message from the broker – user6248190 May 03 '16 at 13:39
  • I mean the value. Check Omid Zamani answer. You code doesn't even compile. Show the error. – Héctor May 03 '16 at 13:42
  • Toast needs a Android context variable as well the text and show duration – hardillb May 03 '16 at 13:47
  • you should remove your async task and put your mqtt inside the activity. Set up mqtt in onCreate and implement MqttCallback in your Activity. The reason why it didnt show is because the AsyncTask has finish. – Spurdow May 03 '16 at 14:15
  • @Spurdow how would I connect to the mqtt broker without Async Task? – user6248190 May 03 '16 at 14:20
  • @Spurdow thanks I have removed the async task and it is connected via the on create method but still cannot display the toast – user6248190 May 03 '16 at 14:50
  • Use the context the activity is using MainActivity.this or this – Spurdow May 03 '16 at 14:52
  • And be sure that you are subscribed – Spurdow May 03 '16 at 14:53
  • The MQTT client connection should be done in an async task because it does network IO so should NOT be done on the main/UI thread – hardillb May 03 '16 at 14:54
  • @hardillb yes that is true, but the op wants to see the toast regardless of how the connection should be implemented – Spurdow May 03 '16 at 14:56
  • @Spurdow yes i am, the message is showing in the console but not in the toast – user6248190 May 03 '16 at 14:57
  • Then you have successfully connected and subscribed, now leave the app as is, and send a message again – Spurdow May 03 '16 at 14:58
  • Toast still isn't working, please see the updated code – user6248190 May 03 '16 at 15:02
  • btw add some code to reconnect when `connectionLost` happens like these `void connect(){ MqttConnectOptions mqttConnectOps = new MqttConnectOptions(); mqttConnectOps .setCleanSession(true); client.connect(mqttConnectOps ); client.setCallback(this); client.subscribe("test"); }` `connectionLost(){ connect(); }` – Spurdow May 03 '16 at 15:16

3 Answers3

1

try this:

Toast.makeText(getApplicationContext(),message.getPayload(),Toast.LENGTH_SHORT).show();

Omid Zamani
  • 414
  • 1
  • 3
  • 15
0

message.getPayload() is an array of bytes docs here https://www.eclipse.org/paho/files/javadoc/org/eclipse/paho/client/mqttv3/MqttMessage.html#getPayload()

you should do this instead

If you are in activity

Toast.makeText(MainActivity.this,new String(message.getPayload()),Toast.LENGTH_SHORT).show();

Hope it helps :)

Spurdow
  • 2,025
  • 18
  • 22
  • i am doing it in Async Task. that is not working either – user6248190 May 03 '16 at 13:51
  • hmm, are you using it inside the `doInBackground`? – Spurdow May 03 '16 at 13:52
  • 1
    ok, you must show your code so that we can fix it., But your question is about red underline in the code, Toast.makeText doesnt require an array of bytes instead it requires a `CharacterSequence`. If it doesnt show and it compiles and run then you must understand that Toast runs in the main thread. – Spurdow May 03 '16 at 13:56
  • wait sorry where am I making my mqtt message final and where am I putting the code you just posted? – user6248190 May 03 '16 at 14:03
  • so everytime you receive a message you run a AsyncTask? btw show all your code. – Spurdow May 03 '16 at 14:08
0

Do not use RunOnUithread. You should use a Handler which could communicate asynchronously between main thread and other threads.

anyway, this could not work.

Toast.makeText(this,new String(message.getPayload()),Toast.LENGTH_SHORT).show();

"this" is the runnable object and not the activity context. So you should pass the context instead of "this". And you have to pass a CharSequence instead of a string. This could work:

CharSequence cs = new String(message.getPayload());
Toast.makeText(getApplicationContext(), cs, Toast.LENGTH_SHORT).show();

Edit: Thanks Spurdow for your hint that a AppCompatActivity is used and instead of "getApplicationContext()" the following should be used.

CharSequence cs = new String(message.getPayload());
Toast.makeText(MainActivity.this, cs, Toast.LENGTH_SHORT).show();
Ben
  • 696
  • 9
  • 19