0
私はSmarthome卒業プロジェクトを持っていて、MQTTプロトコルを使ってクラウドとそれを制御するアンドロイドアプリケーションと通信します。なぜ私はAndroidアプリケーション全体に対して1つのMqttAndroidClientを持つことができないのですか?
私は一つだけ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);
を発生しますが、パラメータとしてMqttAndroidClientを渡すいくつかのトグルボタンの同じパブやSUB5方法であり、それがこのコード
0123のように動作するコードです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();
}
});
何が間違っていて、アイデアや助けがありますか?