我是java编程新手。我在这里遇到了一些问题,有人可以发表评论吗?当我 checkin onLocationChanged()
时。 lngpoint
和 latpoint
存在所需值。但是当我调用另一个方法时,loadcooperative()
、loc.latpoint
和loc.lngpoint
会变为零?为什么?
编辑..基本上我的代码是这样的:
public class Testgpslocation extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Button gpsButton = (Button) findViewById(R.id.gpsButton);
LocationManager a = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
a.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new MyLocationListener());
gpsButton.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v){
LoadCoords();
}});
}
MyLocationListener loc;
public void LoadCoords(){
loc = new MyLocationListener();
String message = String.format(
"wao New Location \n Longitude: %1$s \n Latitude: %2$s",
loc.latpoint, loc.lngpoint
);
Toast.makeText(Testgpslocation.this, message, Toast.LENGTH_LONG).show();
TextView latText = (TextView) findViewById(R.id.latText);
TextView lngText = (TextView) findViewById(R.id.lngText);
double latitude = loc.latpoint;
double longtitude = loc.lngpoint;
latText.setText(Double.toString(latitude));
lngText.setText(Double.toString(longtitude));
}
在另一个类中:
private class MyLocationListener implements LocationListener {
private double latpoint;
private double lngpoint;
public void onLocationChanged(Location location) {
this.latpoint = location.getLatitude();
this.lngpoint = location.getLongitude();
String message = String.format(
"New Location \n Longitude: %1$s \n Latitude: %2$s",latpoint, lngpoint
);
Toast.makeText(Testgpslocation.this, message, Toast.LENGTH_LONG).show();
}
@Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
@Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
}
}
最佳答案
我相信 LocationListener loc 应该在类作用域中定义,而不是在构造函数中定义,就像这样
Public class A{
MyLocationListener loc;
public void loadcoordinate(){
loc = new MyLocationListener();
loc.latpoint, loc.lngpoint;
}
}
关于java - 从另一个类调用变量时失败。 (JAVA),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8505555/