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和经度在这个函数中正确设置,因为我得到了我的当前位置(我在这里粘贴了整个代码,因为这样做没有意义) 这里是我在类中写的代码,我想访问这些变量从另一个类访问一个类的变量
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();
}
再次我没有复制粘贴整个code.This代码工作正常自己,但现在修改它发送消息“Help0.0”等根据我的纬度值应该改变到我目前的位置。请帮助我。
提示:使用变量名称如a或b ...可能会节省5秒用于输入;但是为了理解它们的含义,每个读者花费几分钟和几分钟的时间。换句话说:使用**有意义的**名称。 **总是**。 – GhostCat
据我可以从所示的片段中读取,你是“实例化一个新的'Page3'”,但是,它的'Object.property'a没有准备好被使用,并且你正在使用它。你的'MyLocationListener'没有时间去更新正确的变量。可以保存该值,使用Singleton保存正确的值,或者只在使用该值时使用该值。 – Bonatti
@GhostCat下次会记住这一点。 –