Search code examples
javaandroidgoogle-mapsandroid-fusedlocation

getLastLocation().addOnSuccessListener not work in the button


I want to set a button, when I put the button, then get location.

FusedLocationProviderClient userLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);

This can work in onCreate, but I want to set a button, when I put the button, then show me user location. It can't work. There is my code, how do I fix it?

public class MainActivity extends AppCompatActivity{

final private int userAgreePermissionCode = 1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //  Check permission and go "onRequestPermissionsResult"
    int currentPermission = ActivityCompat.checkSelfPermission(this,android.Manifest.permission.ACCESS_FINE_LOCATION);
    if( currentPermission!=PackageManager.PERMISSION_GRANTED ) ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, userAgreePermissionCode);



    findViewById(R.id.Locate).setOnClickListener(new View.OnClickListener() {
        @SuppressLint("MissingPermission")
        @Override
        public void onClick(View v) {
            //  can't work
            FusedLocationProviderClient userLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);  //  Error in here!!
            userLocationProviderClient.getLastLocation().addOnSuccessListener(new OnSuccessListener<Location>() {
                @Override
                public void onSuccess(Location location) {
                    Log.i("Longitude:", location.getLongitude()+"");
                    Log.i("Latitude:", location.getLatitude()+"");
                }
            });
        }
    });
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    switch (requestCode) {
        case userAgreePermissionCode:
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Permission Granted
                Log.i("Status:","Granted");
            } else {
                // Permission Denied
                finish();
            }
            break;
        default:
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

}

}


Solution

  • It does not work because this in that scope refers to an instance of View.OnClientListener.

    You can fix it by putting MainActivity.this instead, or you can just have FusedLocationProviderClient as member field, instantiate it in onCreate, then use it within your click listener.