0

I am new to Paho android Service and MQTT protocol. I have been trying to write a simple code that connects to the mqtt broker through "xx.xx.xx.xxx:1883". When i run the below posted code, it generates the logcat output.

why i am getting this NPE?

note:

I have the mosquitto server installed

line_35

client.connect(mContext, new IMqttActionListener() {

Code:

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)
4

1 回答 1

1

mContext为空,你需要初始化它。

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

client.connect(getApplicationContext(), new IMqttActionListener(){...});
于 2014-11-13T10:06:51.807 回答