繁体   English   中英

从另一个类访问一个类的变量

[英]Acessing a variable of one class from another

public class Page3 extends Activity {
double latitude;
double longitude;

/**
 * Called when the activity is first created.
 */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.page3);
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
            .permitAll().build();
    StrictMode.setThreadPolicy(policy);
  /* Use the LocationManager class to obtain GPS locations */
    LocationManager mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    LocationListener mlocListener = new MyLocationListener();
    try {
        mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
    } catch (SecurityException e) {
        e.printStackTrace();
    }
}

/* Class My Location Listener */
public class MyLocationListener implements LocationListener {
    @Override
    public void onLocationChanged(Location loc) {

        double a = loc.getLatitude();
        latitude=a;

        double b = loc.getLongitude();
        longitude=b;
        String Text = "My current location is: " +
                "Latitud = " + loc.getLatitude() +
                "Longitud = " + loc.getLongitude();


        String x = getCompleteAddressString(a, b);
        TextView text = (TextView) findViewById(R.id.tv_address);
        text.setText(x);
    }

现在,我想访问另一个类中的变量纬度和经度。这是我需要访问这些变量的类。请注意:纬度和经度的值在此函数中设置正确,因为我获得了当前位置(我把整个代码粘贴在这里,因为这样做没有意义)这是我在类中编写的代码,我想在其中访问这些变量

public class Page2 extends Activity {
/**
 * ATTENTION: This was auto-generated to implement the App Indexing API.
 * See https://g.co/AppIndexing/AndroidStudio for more information.
 */
private GoogleApiClient client;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.page2);
    Button btn = (Button) findViewById(R.id.help);
    Page3 a=new Page3();
    final double lati=a.latitude;
    double longi=a.longitude;
    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            sendSMS("9740641023", "Help"+lati+"");
        }
    });
    // ATTENTION: This was auto-generated to implement the App Indexing API.
    // See https://g.co/AppIndexing/AndroidStudio for more information.
    client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}

我再次没有复制粘贴整个代码。这段代码本身运行良好,但现在修改它发送消息“Help0.0”,尽管据我说纬度值应该已更改为我当前的位置。请执行帮帮我。

您的问题基本上是一个方法中创建了一个实例:

LocationListener mLocListener = new MyLocationListener();

相反,您应该使其成为该类的字段

而且,如果您将其设为公共静态字段,则其他类可以使用

LocationListener theListner = Classname.mLocListener;

但这只是一种非常“蛮力”的做事方式。 所以,你可以用它来看看你是否可以从那里取得进展; 但问题是:直接从其他类访问静态字段是不好的做法; 你应该避免它。

真正的教训是:这是非常基本的“java 知识”。 你现在应该退出“android”; 研究那些基本的 Java 事物(例如:“访问其他对象中信息的合理方法是什么”)。 否则,你会一堵又一堵墙!

然后,当您了解这些基础知识时; 比你看看好书/关于Android教程,向你解释如何“机器人世界”的作品。 因为 Android 有时会使用非常特殊的方式来完成任务。

在 First.java 类中将该变量声明为public static double lattitiue

现在您可以使用First.lattitude在任何类中获取此变量的值

良好的数据抽象和封装允许类的客户端只看到类允许客户端看到的内容。 其他类不应直接访问类 Page3 中的数据成员(如变量 latitude 和 longitude)。 您应该拥有公共 getter(访问器)和 setter(mutator)方法来限制对应声明为私有的数据成员的“访问”。

Java 中只能继承一个类,但可以实现任意多个接口。 因此,您不需要 Page3 类中的内部公共类 MyLocationListener。 只需使用implement 关键字并覆盖接口的方法。

public class Page3 extends Activity implements LocationListener { // implement the interface instead of creating an inner class
    private double latitude; // hide your data members from the client
    private double longitude; 

/**
 * Called when the activity is first created.
 */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.page3);
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
        .permitAll().build();
    StrictMode.setThreadPolicy(policy);
    /* Use the LocationManager class to obtain GPS locations */
    LocationManager mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

try {
    mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this); // pass in this referring to the current class since implementing the interface LocationListener
} catch (SecurityException e) {
    e.printStackTrace();
}

@Override
public void onLocationChanged(Location loc) {

    setMyLatitude(loc.getLatitude()); // use mutator method to change value of your private data member
    setMyLongitude(loc.getLongitude()); // use mutator method to change value of your private data member
    String Text = "My current location is: " +
            "Latitud = " + loc.getLatitude() +
            "Longitud = " + loc.getLongitude();


    String x = getCompleteAddressString(a, b);
    TextView text = (TextView) findViewById(R.id.tv_address);
    text.setText(x);
}

public void setMyLatitude(double a) {
    this.latitude = a;
}

public void setMyLongitude(double b) {
     this.longitude = b;
}

public double getMyLatitude() {
     return latitude;
}

public double getMyLongitude() {
     return longitude;
}
}

现在在第二个活动中使用您的公共方法访问您的数据成员。

public class Page2 extends Activity {
/**
 * ATTENTION: This was auto-generated to implement the App Indexing API.
 * See https://g.co/AppIndexing/AndroidStudio for more information.
 */
 private GoogleApiClient client;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.page2);
    Button btn = (Button) findViewById(R.id.help);
    Page3 a=new Page3();
    final double lati=a.getMyLatitude();
    double longi=a.getMyLongitude();
    btn.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            sendSMS("9740641023", "Help"+lati+"");
         }
     });
     // ATTENTION: This was auto-generated to implement the App Indexing API.
     // See https://g.co/AppIndexing/AndroidStudio for more information.
     client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();

}

这是为了良好的编程习惯。 在两个活动之间进行通信的侦听器可能是您不需要获得 0.0 的初始化双精度值所需要的。 侦听器应在 Page2 类中实现,并带有一个数据成员,该数据成员设置为 Page2 类 Page3 中的侦听器。 侦听器将有一些方法来传递您想要的数据或告诉类 Page2 信息已以某种方式修改。

public class Page2 extends Activity implements DataListener {
.......
@Override
public void someMethod() {
    // do something with the data longitude and latitude as their values have changed
 }
private GoogleApiClient client;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.page2);
    Button btn = (Button) findViewById(R.id.help);
    Page3 a=new Page3();
    a.setDataListener(this); // pass listener to the other class
/* code in Page2 */
}

public class Page3 extends Activity implements LocationListener {
private DataListener myListener;
/* code in Page3 */

@Override
public void onLocationChanged(Location loc) {

    setMyLatitude(loc.getLatitude()); // use mutator method to change value of your private data member
    setMyLongitude(loc.getLongitude()); // use mutator method to change value of your private data member
     myListener.someMethod();  // call this method to inform the other class that information has changed
String Text = "My current location is: " +
        "Latitud = " + loc.getLatitude() +
        "Longitud = " + loc.getLongitude();


String x = getCompleteAddressString(a, b);
TextView text = (TextView) findViewById(R.id.tv_address);
text.setText(x);
}

public void setDataListener(DataListener listener) {
    this.myListener = listener;
}

您还可以将经度和纬度直接传递到 Page3 中的“DataListener”方法“someMethod”中,甚至不需要 Page3 类的 getter 和 setter 以及私有数据成员。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM