连接到经纪人时的NPE

时间:2014-11-13 10:01:08

标签: android mqtt messagebroker mosquitto

我是Paho android ServiceMQTT协议的新手。我一直在尝试编写一个通过mqtt连接到"xx.xx.xx.xxx:1883"代理的简单代码。当我运行以下发布的代码时,它会生成logcat输出。

为什么我得到这个NPE

注释

我有mosquitto server installed

line_35

client.connect(mContext, new IMqttActionListener() {

代码

private Context mContext;
private final String serverURI = "xx.xx.xx.xx:1883";
private final String clientID = MqttClient.generateClientId();
private MqttAndroidClient client = null;
private final String TAG = this.getClass().getSimpleName();
 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.mqtt__proj_00_layout);

        MqttAndroidClient client = new MqttAndroidClient(mContext, serverURI, clientID);
        if (client != null) {
            try {
                client.connect(mContext, new IMqttActionListener() {

                    @Override
                    public void onSuccess(IMqttToken arg0) {
                        // TODO Auto-generated method stub
                        Log.i(TAG, "Connection Successful.");
                    }

                    @Override
                    public void onFailure(IMqttToken arg0, Throwable arg1) {
                        // TODO Auto-generated method stub
                        Log.i(TAG, "Connection Failed.");
                    }
                });
            } catch (MqttException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

}

logcat的

11-13 10:51:07.913: E/AndroidRuntime(26656): FATAL EXCEPTION: main
11-13 10:51:07.913: E/AndroidRuntime(26656): Process: com.example.mqtt_proj_00, PID: 26656
11-13 10:51:07.913: E/AndroidRuntime(26656): java.lang.RuntimeException: Unable to start activity  
ComponentInfo{com.example.mqtt_proj_00/com.example.mqtt_proj_00.MQTT_Proj_00}:   
java.lang.NullPointerException
11-13 10:51:07.913: E/AndroidRuntime(26656):    at 
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2282)
11-13 10:51:07.913: E/AndroidRuntime(26656):    at   
com.example.mqtt_proj_00.MQTT_Proj_00.onCreate(MQTT_Proj_00.java:35)

1 个答案:

答案 0 :(得分:1)

mContext为空,您需要对其进行初始化。

你可以通过替换mContext(如果你没有在其他地方使用它)来做到这一点:

client.connect(getApplicationContext(), new IMqttActionListener(){...});