Skip to content Skip to sidebar Skip to footer

Get The User's Current City

Hi I posted a question concerning the same topic a while ago, after following your advices I can feel that I'm getting closed to solving my problem. The App does is now crashing as

Solution 1:

in the condition if (addresses != null) { } you should also check for the length of the addresses, since there might be 0.

if (addresses != null && addresses.size() > 0) {
    Stringaddress= addresses.get(0).getAddressLine(0);
    Stringcity= addresses.get(0).getLocality();
    Stringstate= addresses.get(0).getAdminArea();
    Stringcountry= addresses.get(0).getCountryName();
    StringpostalCode= addresses.get(0).getPostalCode();
    StringknownName= addresses.get(0).getFeatureName();

    mProgressDialog.dismiss();
    TextViewcellText= (TextView) findViewById(R.id.cellText);
    cellText.setText(address);

} else {
    mProgressDialog.dismiss();
    TextViewcellText= (TextView) findViewById(R.id.cellText);
    cellText.setText("Error");
}

if it wasn't able to find at least one address you should consider showing the user an empty state.

It also seems like you forgot to initialize your latitude and longitude before calling addresses = geocoder.getFromLocation(lat, lon, 1);

To properly initialize this, do the following:

Location location = intent.getParcelableExtra(__YOUR_PACKAGE_NAME__ + ".LOCATION_DATA_EXTRA");
lat = location.getLatitude();
lon = location.getLongitude();

If you need any more help check out this page from android. It should hold all information you need.

EDIT:

I kind of assumed you we're further in the process, but it seems you have only tried to get the location of a latLong position, which you have never obtained. To achieve obtaining the address you will have to have the user's lcoation first.

Again, the page mentioned above should explain everything you need to obtain the location, but make sure of the following:

1. Have the permission to access the user's location (for Android 6+ use Runtime permissions)

<manifestxmlns:android="http://schemas.android.com/apk/res/android"package="com.google.android.gms.location.sample.locationupdates" ><uses-permissionandroid:name="android.permission.ACCESS_FINE_LOCATION"/></manifest>

2. Get an instance of the GoogleApi and ave your activity implement some callbacks

For the Callbacks

publicclassYourActivityextendsAppCompatActivityimplementsConnectionCallbacks, OnConnectionFailedListener

Then in your OnCreate() create an instance of GoogleApiClient.

protectedGoogleApiClient mGoogleApiClient;

publicvoidonCreate(Bundle savedInstanceState) {
    mGoogleApiClient = newGoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
    mGoogleApiClient.connect();
}

3. Obtain the location from the GoogleApiClient Do this by implementing the callbacks properly.

/**
 * Represents a geographical location.
 */protectedLocation mLastLocation;

@OverridepublicvoidonConnected(Bundle connectionHint) {
     // Gets the best and most recent location currently available, which may be null// in rare cases when a location is not available.
     mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
     if (mLastLocation != null) {
         // Determine whether a Geocoder is available.if (!Geocoder.isPresent()) {
             Toast.makeText(this, "no geocoder available", Toast.LENGTH_LONG).show();
             return;
         }
     }
 }

4. Now obtain the lat long and try to obtain the address as attempted before.

lat = mLastLocation.getLatitude();
lon = mLastLocation.getLongitude();

geocoder = new Geocoder(MainActivity.this, Locale.getDefault());
List<Address> addresses = null;
try {
    addresses = geocoder.getFromLocation(lat, lon, 1);
} catch (IOException e) {
    e.printStackTrace();
}

This should be enough to obtain the actual adress of the device and ask the geocoder for the addresses. I altered the example a bit to simplify for this question. Google's example handles fetching the address a bit more clean. Note that you will also have to disconnect the GoogleApi when stopping your activity and such. Again I recommend reading the entire Tutorial page. You can find en example of their implementation on this page on GitHub

Post a Comment for "Get The User's Current City"