0

I am trying to get address from current latitude and longitude,but my List getting nothing it always shows empty/null. this is my javacode :

    public void onConnected(Bundle bundle) {

    Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
    if (location == null) {
             LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,        mLocationRequest, (LocationListener) this);

    } else {
        //If everything went fine lets get latitude and longitude
        double currentLatitude = location.getLatitude();
        double currentLongitude = location.getLongitude();

        Toast.makeText(this, currentLatitude + " WORKS " + currentLongitude + "", Toast.LENGTH_LONG).show();
    }


    geocoder = new Geocoder(MainActivity.this, Locale.getDefault());
    try {
        yourAddresses= geocoder.getFromLocation(currentLatitude,currentLongitude, 1);
        if (yourAddresses.size() > 0)
        {
            //String yourAddress = yourAddresses.get(0).getAddressLine(0);
            String yourCity = yourAddresses.get(0).getAddressLine(1);
            //String yourCountry = yourAddresses.get(0).getAddressLine(2);
            TextView city = (TextView)findViewById(R.id.cityname);
            city.setText(" "+yourCity);
            Toast.makeText(this," "+ yourCity,Toast.LENGTH_LONG).show();
        }
    } catch (IOException e) {
        e.printStackTrace();
        Toast.makeText(this,""+e,Toast.LENGTH_LONG).show();
    }

}

I am getting current latitude and longitude but not address belongs to respective latitude and longitude.

Abhijeet
  • 481
  • 1
  • 6
  • 14

1 Answers1

0

I am getting current latitude and longitude

First Make double currentLatitude and double currentLongitude Global

double currentLatitude;
double currentLongitude;

because your geocoder does not get the updated latitude and longitude. it is only visible to the local block.

else {
    //If everything went fine lets get latitude and longitude
    currentLatitude = location.getLatitude();   //change
    currentLongitude = location.getLongitude();

    Toast.makeText(this, currentLatitude + " WORKS " + currentLongitude + "", Toast.LENGTH_LONG).show();
}
yourAddresses= geocoder.getFromLocation(currentLatitude,currentLongitude, 1);

Also change this:

String yourCity = yourAddresses.get(0).getAddressLine(1);

to :

String yourCity = yourAddresses.get(0).getAddressLine(0);
rafsanahmad007
  • 23,683
  • 6
  • 47
  • 62