首页 > 解决方案 > 我想从类 2 访问类 1 的对象 **object** 来自另一个类让我们说类 3

问题描述

下面是声明为“客户端”的对象,我导入的另一个名为 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

标签: javaandroidandroid-studiooop

解决方案


首先将 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();

推荐阅读