下面是声明为"client"的对象,我导入的另一个类称为mqttAndroidClient
public class connection{
public void onCtreate(){
String clientId = MqttClient.generateClientId();
MqttAndroidClient client =
new MqttAndroidClient(getApplicationContext(), "tcp://" + TEXT + ":" + TEXT2,
clientId);
}
}
the object "client" of connection class, i wanna access it from a main class
public class main extends AppComptActivity{
//
//Attributes
//
public void onCreate(){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//onclick of button
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String topic = TOPIC;
String payload = PAYLOAD;
byte[] encodedPayload = new byte[0];
try {
encodedPayload = payload.getBytes("UTF-8");
MqttMessage message = new MqttMessage(encodedPayload);
message.setRetained(true);
client.publish(topic, message);
} catch (UnsupportedEncodingException | MqttException e) {
e.printStackTrace();
}
}
});
}
在上面的代码中,它无法将客户端标识为连接类中的对象
client.publish(topic, message);
i have tried to call it in main using
connection myobject = new connection(); myobject.onCreate();
but its throwing a declaration error i am very new to java and oops and
if the info is not efficient i will post the full code
首先,将 Connection 类中的客户端对象作为全局变量,并调用初始化对象的构造函数。
public class Connection {
MqttAndroidClient client;
Context context;
public Connection(Context context) {
this.context = context;
initClient(context);
}
public void initClient(Context context){
client =
new MqttAndroidClient(getApplicationContext(), "tcp://" + TEXT1 + ":" + TEXT2,
clientId);
}
public MqttAndroidClient getClient(){
return client;
}
}
现在MainClass
首先获取Connection class
的对象,然后通过调用返回客户端对象的方法从连接类中获取客户端对象。
主类内部
Connection connection= new Connection(this);
MqttAndroidClient client= connection.getClient();
让我猜猜问题 - 您想从onClick
方法中访问client
,以便可以调用client.publish(topic, message);
,但现在您遇到编译错误。 我说的对吗?
原因 :MqttAndroidClient client
onCtreate
方法中的connection
是一个局部变量,在调用onCtreate
之后创建和销毁。 因此它是不可访问的。
解决方案:使MqttAndroidClient client
成为connection
类的属性。
更新连接类,如下所示:
public class connection{
private MqttAndroidClient client;
public MqttAndroidClient getClient(){
return this.client;
}
public void onCreate(){
String clientId = MqttClient.generateClientId();
this.client =
new MqttAndroidClient(getApplicationContext(), "tcp://" + TEXT + ":" + TEXT2,
clientId);
}
现在在下面的方法中,您可以添加
connection myobject = new connection();
myobject.onCreate();
myobject.getClient().publish(topic, message);