从另一个类中获取一个类的变量

时间:2016-10-10 12:05:41

标签: java android class variables

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);
    }

现在,我想在另一个类中访问变量纬度和经度。这是我需要访问这些变量的类。请注意:latitiude和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.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"虽然根据我的说法,纬度值应该已经改变到我当前的位置。请帮帮我。

3 个答案:

答案 0 :(得分:1)

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

LocationListener mLocListener = new MyLocationListener();

相反,您应该将其设为该类的字段

而且,如果你创建一个公共静态字段,那么其他类可以使用

直接访问它
LocationListener theListner = Classname.mLocListener;

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

真正的教训是:这是非常基本的" java知识"。你应该退出" android"目前;并且学习那些基本的Java事物(例如:"什么是合理的方式来访问其他对象中的信息")。否则,你会一个接一个地撞墙!

然后,当你理解那些基础知识;比你看看关于Android的好的书籍/教程,向你解释" Android世界"作品。因为Android有时会使用非常特殊的方式来完成任务。

答案 1 :(得分:0)

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

现在您可以使用First.lattitude

在任何类中获取此变量的值

答案 2 :(得分:0)

良好的数据抽象和封装允许类的客户端只能看到类允许客户端看到的内容。您的数据成员(如类Page3中的变量纬度和经度)不应由其他类直接访问。你应该有公共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的初始化double值。监听器应该在类Page2中实现,其中一个数据成员设置为类Page3中Page2中的监听器。监听器将有一些方法可以传递您想要的数据,或者告诉类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;
}

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