문제

I'm trying to enable/disable GPS services by a ToggleButton. The app starts with the button unchecked, and GPS services are disabled (as they should be). They turn on successfully and works great BUT when I turn it off again, it crashes. Here's the code:

    final LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
    final LocationListener locationListener = null;
    final ToggleButton gpsButton = (ToggleButton) findViewById(R.id.gpsButton);


    gpsButton.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            // TODO Auto-generated method stub

            if (gpsButton.isChecked()) {
                 LocationListener locationListener = new LocationListener() {
                    public void onLocationChanged(Location location) {
                      // Called when a new location is found by the network location provider.

                        //doing some stuff with locations


                    }

                    public void onStatusChanged(String provider, int status, Bundle extras) {}

                    public void onProviderEnabled(String provider) {}

                    public void onProviderDisabled(String provider) {}
                  };
                  locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, seconds, 0, locationListener);
            }
            else {
                locationManager.removeUpdates(locationListener);
            }
        }
도움이 되었습니까?

해결책

You are declaring the locationListener outside of the onClickListener, but then creating a new local locationListener variable when the user clicks the button.

It is still null when you try to remove updates from it because you have created a different variable. Remove the type declaration from locationListener in the onClick method, so it becomes

...
if (gpsButton.isChecked()) {
    locationListener = new LocationListener() {
    ...
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top