FORUMS
Remove All Ads from XDA

class problem

1 posts
Thanks Meter: 0
 
By kozzen8980, Junior Member on 15th November 2019, 09:12 PM
Post Reply Email Thread
I'm having a class Mqtt with this code as below :

Code:
package com.example.myhome;

import org.eclipse.paho.android.service.MqttAndroidClient;
import org.eclipse.paho.client.mqttv3.IMqttActionListener;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
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.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttPersistenceException;

import android.content.Context;
import android.content.DialogInterface;
import android.util.Log;

import androidx.appcompat.app.AlertDialog;

import java.io.UnsupportedEncodingException;

public class Mqtt {

    public MqttAndroidClient mqttAndroidClient;

    final String serverUri = "tcp://***";
    final String clientId = "***";

    final String username = "***";
    final String password = "***";

    public Mqtt(Context context) {
        mqttAndroidClient = new MqttAndroidClient(context, serverUri, clientId);
        mqttAndroidClient.setCallback(new  MqttCallback() {
            //@Override
            public void connectComplete(boolean b, String s) {
                Log.w("mqtt", s);
            }

            @Override
            public void connectionLost(Throwable throwable) {

            }

            @Override
            public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
                Log.w("Mqtt", mqttMessage.toString());
            }

            @Override
            public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {

            }
        });
        connect();
    }

    public void setCallback(MqttCallback callback) {
        mqttAndroidClient.setCallback(callback);
    }

    private void connect() {
        MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
        //mqttConnectOptions.setAutomaticReconnect(true);
        mqttConnectOptions.setCleanSession(false);
        mqttConnectOptions.setUserName(username);
        mqttConnectOptions.setPassword(password.toCharArray());

        try {

            mqttAndroidClient.connect(mqttConnectOptions, null, new IMqttActionListener() {
                @Override
                public void onSuccess(IMqttToken asyncActionToken) {

                   //DisconnectedBufferOptions disconnectedBufferOptions = new DisconnectedBufferOptions();
                   // disconnectedBufferOptions.setBufferEnabled(true);
                   // disconnectedBufferOptions.setBufferSize(100);
                    //disconnectedBufferOptions.setPersistBuffer(false);
                    //disconnectedBufferOptions.setDeleteOldestMessages(false);
                   // mqttAndroidClient.setBufferOpts(disconnectedBufferOptions);

                    subscribeToTopic("esp/test");
                    //publishToTopic("esp/test","POPdd");
                }

                @Override
                public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                    Log.w("Mqtt", "Failed to connect to: " + serverUri + exception.toString());
                }
            });


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


    private void subscribeToTopic(String Topic) {
        try {
            mqttAndroidClient.subscribe(Topic, 0, null, new IMqttActionListener() {
                @Override
                public void onSuccess(IMqttToken asyncActionToken) {
                    Log.w("Mqtt", "Subscribed!");
                }

                @Override
                public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                    Log.w("Mqtt", "Subscribed fail!");
                }
            });

        } catch (MqttException ex) {
            System.err.println("Exceptionst subscribed");
            ex.printStackTrace();
        }
    }
    public void publishToTopic(MqttAndroidClient client,String Topic,String MessageForTopic) {

        String payload = MessageForTopic ;

        byte[] encodedPayload = new byte[0];
        try {
            encodedPayload = payload.getBytes("UTF-8");
            MqttMessage message = new MqttMessage(encodedPayload);
            client.publish(Topic, message,null,new IMqttActionListener() {
               // @Override
               public void onSuccess(IMqttToken asyncActionToken) {
                    Log.w("Mqtt", "Published!");
                }

                @Override
                public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                    Log.w("Mqtt", "Published fail!");
               }
            });
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (MqttPersistenceException e) {
            e.printStackTrace();
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }
}
i have also a class Hoofdmenu (code below) with a layout. Here i want to send a message into the mqtt
=> MqttCommunicatie.publishToTopic(MqttCommunicatie.m qttAndroidClient,"esp/test","Message MQTT");
when i publishToTopic after the subscribe into class Mqtt the i receive the message when i ask into the class Hoofdmenu it doens't work

what do i do wrong ? Or wht can i do to to it work ?
now receive the message "MyHome is stopped Open app again"

Code:
package com.example.myhome;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;

import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.example.myhome.HoofdmenuTabs.PagerAdapter;
import com.google.android.material.tabs.TabLayout;


import org.eclipse.paho.android.service.MqttAndroidClient;
import org.eclipse.paho.client.mqttv3.IMqttActionListener;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttPersistenceException;

import java.io.UnsupportedEncodingException;

public class Hoofdmenu extends AppCompatActivity {

    public Mqtt MqttCommunicatie;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_hoofdmenu);

        TabLayout tabMenu = (TabLayout) findViewById(R.id.tabMenu);


        final ViewPager viewPager = (ViewPager) findViewById(R.id.tabpager);
        final PagerAdapter adapter = new PagerAdapter
                (getSupportFragmentManager(), tabMenu.getTabCount());
        viewPager.setAdapter(adapter);
        viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabMenu));

        tabMenu.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                viewPager.setCurrentItem(tab.getPosition());

            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
            }
        });

        startMqtt();
        MqttCommunicatie.publishToTopic(MqttCommunicatie.mqttAndroidClient,"esp/test","Message MQTT");

    }

    private void startMqtt(){
        MqttCommunicatie = new Mqtt(getApplicationContext());
        MqttCommunicatie.setCallback(new MqttCallback() {
            //@Override
            public void connectComplete(boolean b, String s) {

            }

            @Override
            public void connectionLost(Throwable throwable) {

            }

            @Override
            public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
                Log.w("Debug", mqttMessage.toString());
                //dataReceived.setText(mqttMessage.toString());
            }

            @Override
            public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {

            }
        });
    }
}
Post Reply Subscribe to Thread

Guest Quick Reply (no urls or BBcode)
Message:
Previous Thread Next Thread
Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes