我有一个Smarthome毕业项目,它使用MQTT协议与云和一个控制它的Android应用程序进行通信。
我试图仅创建一个MqttAndroidClient并在所有活动中使用它并且不起作用,当我尝试将同一个客户端传递给另一个发布或订阅方法时,我收到错误类
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.badr.said.muhammad.smarthome/com.badr.said.muhammad.smarthome.Welcome}: java.lang.NullPointerException: Attempt to invoke virtual method 'org.eclipse.paho.client.mqttv3.IMqttDeliveryToken org.eclipse.paho.android.service.MqttService.publish(java.lang.String, java.lang.String, byte[], int, boolean, java.lang.String, java.lang.String)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
这是发生错误的代码
public class Welcome extends AppCompatActivity {
MqttAndroidClient client;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
client = new MqttAndroidClient(this.getApplicationContext(),mqtthost,clientId);
MqttConnectOptions options = new MqttConnectOptions();
options.setUserName(username);
options.setPassword(password.toCharArray());
try {
IMqttToken token = client.connect(options);
token.setActionCallback(new IMqttActionListener() {
@Override
public void onSuccess(IMqttToken asyncActionToken) {
Toast.makeText(Welcome.this, "Connected !", Toast.LENGTH_LONG).show();
}
@Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
Toast.makeText(Welcome.this, "Connection Field , Check Your Internet Network !", Toast.LENGTH_LONG).show();
}
});
} catch (MqttException e) {
e.printStackTrace();
}
pub("Smarthome","check",client);
sub5(client);
但是在某些切换按钮上使用相同的pub和sub5方法传递MqttAndroidClient作为参数,它的工作方式与此代码类似
toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
pub("Smarthome", "devicegon1", client);
} else {
pub("Smarthome", "devicegoff1", client);
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
sub();
}
});
那有什么不对,有什么想法或帮助吗?
答案 0 :(得分:1)
您在调用pub()
之前呼叫onSuccess()
,因此当您尝试发布时,您尚未实际连接。
将pub()
和sub5()
移到该回调中,事情应该改进