我的代码面临一个小问题并因此而陷入困境。以下是我的代码:-
public class MainActivity extends Activity {
TextView textView1;
Location currentLocation;
double currentLatitude,currentLongitude;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView1 = (TextView) findViewById(R.id.textView1);
findLocation();
textView1.setText(String.valueOf(currentLatitude) + "\n"
+ String.valueOf(currentLongitude));
}
public void findLocation() {
LocationManager locationManager = (LocationManager) this
.getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
updateLocation(location,currentLatitude,currentLongitude);
Toast.makeText(
MainActivity.this,
String.valueOf(currentLatitude) + "\n"
+ String.valueOf(currentLongitude), 5000)
.show();
}
public void onStatusChanged(String provider, int status,
Bundle extras) {
}
public void onProviderEnabled(String provider) {
}
public void onProviderDisabled(String provider) {
}
};
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
}
void updateLocation(Location location,double currentLatitude,double currentLongitude) {
currentLocation = location;
this.currentLatitude = currentLocation.getLatitude();
this.currentLongitude = currentLocation.getLongitude();
}
}
一切正常。但我的问题是类级别变量 currentLatitude 和 currentLongitude 的值为 null。在上面的代码中,当我在更新位置方法的文本视图中设置纬度和经度时,它工作正常但是当我想要在创建方法中的文本视图中设置相同的值它会给出空值。为什么我不知道。请帮助解决这个问题。提前致谢!