Search code examples
androidandroid-activitygeolocationoncreate

Why onCreate method doesn't execute next lines after getting location with Google Play services location APIs?


In my onCreate method getLocation() method gets information using the Google Play services location APIs. It works well, but after executing getLocation() my onCreate method doesn't execute next lines of code. What shoud I do to execute next lines in my onCreate method after finishing with getLocation()? Thanks!

    public class WeatherActivity extends AppCompatActivity {

    FusedLocationProviderClient mFusedLocationClient;
    TextView locationTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_weather);
        locationTextView = (TextView) findViewById(R.id.locationTextView);
        getLocation();

        //Next line doesn't execute 
        locationTextView.setText("THIS TEXT WILL NEVER APPEAR");
    }

    private void getLocation() {
        mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        mFusedLocationClient.getLastLocation()
                .addOnSuccessListener(this, new OnSuccessListener<Location>() {
                    @Override
                    public void onSuccess(Location location) {
                        if (location != null) {
                            //Setting text to TextView
                            locationTextView.setText("THIS TEXT IS OK");
                        }
                    }
                });
    }
}

Solution

  • The line doesn't execute or it just doesn't behave as you expect? Did you put a breakpoint there and debug it?

    To me it seems that the line executes fine but the text gets quickly overriden by onSuccess callback.

    onSuccess doesn't get called immediatelly but some time in the future. So it's very likely that the line locationTextView.setText("THIS TEXT WILL NEVER APPEAR"); gets executed before the code in onSuccess