簡體   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