不能运行我在Android Studio的MQTT应用 [英] Can't run my MQTT application on Android Studio

查看:1383
本文介绍了不能运行我在Android Studio的MQTT应用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我测试了个人MQTT应用程序,但是当我点击连接按钮,它失败...有一个例外,但我不知道它从何而来。

i'm testing a personal MQTT application but it failed when i click on the connect button... There is an exception but i don't know where it comes from.

下面是我的code

MainActivity.java:

MainActivity.java :

package com.application.phoste.homecontrol;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;


public class MainActivity extends Activity {
    private Paho paho = null;
    EditText topic = null;
    EditText message = null;
    Button connect = null;
    Button send = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        paho = new Paho();

        topic = (EditText) findViewById(R.id.topic);
        message = (EditText) findViewById(R.id.message);

        connect = (Button) findViewById(R.id.connect);
        connect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                paho.connect();
                String res = (paho.isConnected()) ? "Connected" : "Not Connected";
                Toast toast = Toast.makeText(getApplicationContext(), res, Toast.LENGTH_SHORT);
                toast.show();
            }
        });
        send = (Button) findViewById(R.id.send);
        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                paho.publish(topic.getText().toString(), message.getText().toString());
                Toast toast = Toast.makeText(getApplicationContext(), "Message sent", Toast.LENGTH_SHORT);
                toast.show();
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

Paho.java:

Paho.java :

package com.application.phoste.homecontrol;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
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;

public class Paho implements MqttCallback {

    private MqttClient client;
    private static final String BROKER = "tcp://192.168.1.189:1883";
    private static final int QOS = 2;

    public void connect() {
        try {
            client = new MqttClient(BROKER, MqttClient.generateClientId());
            MqttConnectOptions options = new MqttConnectOptions();
            options.setConnectionTimeout(1);
            client.setCallback(this);
            client.connect();
        } catch (MqttException e) {
            e.getMessage();
        }
    }

    public void disconnect() {
        if (client.isConnected()) {
            try {
                client.disconnect();
            } catch (MqttException e) {
                e.getMessage();
            }
        }
    }

    public boolean isConnected() {
        return client.isConnected();
    }

    public void publish(String topic, String m) {
        try {
            MqttMessage message = new MqttMessage(m.getBytes());
            message.setQos(2);
            client.publish(topic, message);
        } catch (MqttException e) {
            e.getMessage();
        }
    }

    @Override
    public void connectionLost(Throwable throwable) {

    }

    @Override
    public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {

    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {

    }
}

例外情况:

07-29 15:17:23.988  15718-15718/com.application.phoste.homecontrol E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.application.phoste.homecontrol, PID: 15718
    java.lang.NullPointerException: Attempt to invoke virtual method 'boolean org.eclipse.paho.client.mqttv3.MqttClient.isConnected()' on a null object reference
            at com.application.phoste.homecontrol.Paho.isConnected(Paho.java:44)
            at com.application.phoste.homecontrol.MainActivity$1.onClick(MainActivity.java:35)
            at android.view.View.performClick(View.java:4756)
            at android.view.View$PerformClick.run(View.java:19748)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5254)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:898)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:693)

我还添加了<使用-权限的Andr​​oid:名称=android.permission.INTERNET对/> 行到AndroidManifest.xml中

I also added the <uses-permission android:name="android.permission.internet"/> line into the AndroidManifest.xml

我在哪里错了?

编辑:

我才意识到我有一些警告信息的异常被抛出之前......在这里,他们是:

I just realized i had some warning messages even before the exception was thrown... Here they are :

07-29 17:26:52.673  32706-32706/com.application.phoste.homecontrol W/System.err﹕ MqttException (0)
07-29 17:26:52.673  32706-32706/com.application.phoste.homecontrol W/System.err﹕ at org.eclipse.paho.client.mqttv3.persist.MqttDefaultFilePersistence.open(MqttDefaultFilePersistence.java:80)
07-29 17:26:52.673  32706-32706/com.application.phoste.homecontrol W/System.err﹕ at org.eclipse.paho.client.mqttv3.MqttAsyncClient.<init>(MqttAsyncClient.java:286)
07-29 17:26:52.674  32706-32706/com.application.phoste.homecontrol W/System.err﹕ at org.eclipse.paho.client.mqttv3.MqttAsyncClient.<init>(MqttAsyncClient.java:167)
07-29 17:26:52.674  32706-32706/com.application.phoste.homecontrol W/System.err﹕ at org.eclipse.paho.client.mqttv3.MqttClient.<init>(MqttClient.java:224)
07-29 17:26:52.674  32706-32706/com.application.phoste.homecontrol W/System.err﹕ at org.eclipse.paho.client.mqttv3.MqttClient.<init>(MqttClient.java:136)
07-29 17:26:52.675  32706-32706/com.application.phoste.homecontrol W/System.err﹕ at com.application.phoste.homecontrol.MainActivity.onCreate(MainActivity.java:35)
07-29 17:26:52.675  32706-32706/com.application.phoste.homecontrol W/System.err﹕ at android.app.Activity.performCreate(Activity.java:5933)
07-29 17:26:52.676  32706-32706/com.application.phoste.homecontrol W/System.err﹕ at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
07-29 17:26:52.676  32706-32706/com.application.phoste.homecontrol W/System.err﹕ at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2282)
07-29 17:26:52.676  32706-32706/com.application.phoste.homecontrol W/System.err﹕ at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2389)
07-29 17:26:52.676  32706-32706/com.application.phoste.homecontrol W/System.err﹕ at android.app.ActivityThread.access$900(ActivityThread.java:147)
07-29 17:26:52.676  32706-32706/com.application.phoste.homecontrol W/System.err﹕ at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1296)
07-29 17:26:52.676  32706-32706/com.application.phoste.homecontrol W/System.err﹕ at android.os.Handler.dispatchMessage(Handler.java:102)
07-29 17:26:52.676  32706-32706/com.application.phoste.homecontrol W/System.err﹕ at android.os.Looper.loop(Looper.java:135)
07-29 17:26:52.676  32706-32706/com.application.phoste.homecontrol W/System.err﹕ at android.app.ActivityThread.main(ActivityThread.java:5254)
07-29 17:26:52.676  32706-32706/com.application.phoste.homecontrol W/System.err﹕ at java.lang.reflect.Method.invoke(Native Method)
07-29 17:26:52.676  32706-32706/com.application.phoste.homecontrol W/System.err﹕ at java.lang.reflect.Method.invoke(Method.java:372)
07-29 17:26:52.676  32706-32706/com.application.phoste.homecontrol W/System.err﹕ at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:898)
07-29 17:26:52.678  32706-32706/com.application.phoste.homecontrol W/System.err﹕ at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:693)

我真的希望有人能够帮助我这一点。

I really hope someone could help me with that.

我也改变了我的code尽在MainActivity:

I also changed my code to do everything in the MainActivity :

package com.application.phoste.homecontrol;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

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;


public class MainActivity extends Activity {
    EditText topic = null;
    EditText message = null;
    Button send = null;
    Button debug = null;
    MqttClient client;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        try {
            client = new MqttClient("tcp://m2m.eclipse.org:1883", MqttClient.generateClientId());
            MqttConnectOptions options = new MqttConnectOptions();
            options.setConnectionTimeout(1);
            client.connect();
        } catch (MqttException e) {
            e.printStackTrace();
        }

        topic = (EditText) findViewById(R.id.topic);
        message = (EditText) findViewById(R.id.message);

        send = (Button) findViewById(R.id.send);
        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    MqttMessage m = new MqttMessage(message.getText().toString().getBytes());
                    m.setQos(2);
                    client.publish(topic.getText().toString(), m);
                    Toast toast = Toast.makeText(getApplicationContext(), "Message sent", Toast.LENGTH_SHORT);
                    toast.show();
                } catch (MqttException e) {
                    e.printStackTrace();
                }
            }
        });

        debug = (Button) findViewById(R.id.debug);
        debug.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String res = (client == null) ? "Null" : "Not Null";
                Toast toast = Toast.makeText(getApplicationContext(), res, Toast.LENGTH_SHORT);
                toast.show();
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

但它仍然无法正常工作,我从去调试按钮获得空吐司。

But it still doesn't work, I get the Null Toast from de debug button.

推荐答案

确定,所以你需要建立MQTT文件持久性的路径,这将需要写访问的SD卡,你给它的路径。

OK, so you need to set up the MQTT file persistence path and this will require write access to the SD card and the path you give it.

<一个href="https://www.eclipse.org/paho/files/javadoc/index.html?org/eclipse/paho/client/mqttv3/persist/MqttDefaultFilePersistence.html" rel="nofollow">https://www.eclipse.org/paho/files/javadoc/index.html?org/eclipse/paho/client/mqttv3/persist/MqttDefaultFilePersistence.html

您还需要添加合适的权限访问该文件系统。

You will also need to add the right permission to access the file system.

这篇关于不能运行我在Android Studio的MQTT应用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆