【发布时间】:2016-10-10 12:05:41
【问题描述】:
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”,尽管根据我的说法,纬度值应该已经更改为我当前的位置.请帮帮我。
【问题讨论】:
-
提示:使用像 a 或 b 这样的变量名...也许可以节省 5 秒的打字时间;但是为了理解他们的意思,每个读者都需要花费几分钟和几分钟。换句话说:使用有意义的名称。 总是.
-
据我从显示的 sn-ps 中可以看出,您正在“实例化一个新的
Page3”,但是,它的Object.propertya 还没有准备好使用,而您正在使用它。您的MyLocationListener没有时间更新正确的变量。要么保存值,要么使用 Singleton 来保存正确的值,或者仅在准备好时使用该值。 -
@GhostCat 下次会记住这一点。
标签: java android class variables