订阅MqttAndroidClient上的主题时出现NullPointerException

时间:2014-11-09 09:56:28

标签: android nullpointerexception mqtt

我使用过Paho Eclipse repo的Android Service jar。我在客户端连接后订阅任何主题时遇到NUllPOinterException。

    public void connect(View view) {

    MqttConnectOptions conOpt = new MqttConnectOptions();

    String uri = "tcp://" + host + ":" + port;
    boolean cleanSession = true;
    // int timeout = 60 ;
    // int keepalive = 60 ;
    clientHandle = uri + clientId;

    MqttAndroidClient client;
    client = Connections.getInstance(this)
            .createClient(this, uri, clientId);

    Connection conn = new Connection(clientHandle, clientId, host, port,
            this, client, sslConnection);

    conOpt.setCleanSession(cleanSession);
    // conOpt.setConnectionTimeout(timeout);
    conOpt.setKeepAliveInterval(100);;

    MqttCallbackHandler callback = new MqttCallbackHandler(this,
            MainActivity.this, clientHandle);

    conn.addConnectionOptions(conOpt);
    Connections.getInstance(this).addConnection(conn);
    String[] topics = { "hello", "hi" };
    int qos = 0;
    try {
        IMqttToken t = client.connect(conOpt, null, new ActionListener(this,
                Action.CONNECT, uri, (String[]) null));
        //t.waitForCompletion(90);
        client.setCallback(callback);
        IMqttToken token = Connections
                .getInstance(this)
                .getConnection(clientHandle)
                .getClient()
                .subscribe(
                        "shatinTopic",
                        qos,
                        null,
                        new ActionListener(this, Action.SUBSCRIBE, uri,
                                topics));
        Log.d("SUBSCRIBE", token.getResponse().toString());
    } catch (MqttException e) {
        e.getCause();
    } catch (NullPointerException e) {
        e.getCause();
    } catch (Exception e) {
        e.getCause();
    }
}

错误:

11-09 15:17:24.702: E/AndroidRuntime(26671): Caused by: java.lang.NullPointerException
11-09 15:17:24.702: E/AndroidRuntime(26671): at      org.eclipse.paho.android.service.MqttAndroidClient.subscribe(MqttAndroidClient.java:788)

有人可以帮助确切地说出错的地方。

提前感谢!

1 个答案:

答案 0 :(得分:4)

从paho dev邮件列表中得到了这个答案。

  

因为connect是异步的,并且连接可能无法建立您调用subscribe的时间。   你应该使用waitForCompletion或者在IMqttActionListener.onSuccess中调用subscribe,如果你使用IMqttToken connect(MqttConnectOptions选项,Object userContext,IMqttActionListener回调)

尽管waitForCompletion给出了服务器超时错误,但订阅onSuccess方法的侦听器解决了这个问题。