Search code examples
javaandroidandroid-studiogeolocation

How to get a user's current city?


I want to get the user's current location through my Android Application. I keep seeing the error message that should be displayed if anything goes wrong getting the location from the phone's GPS. Can you guys please tell me what's wrong with my codes?

MainActivity.java:

package com.example.apple.project;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

public class MainActivity extends AppCompatActivity {

    private static final int MY_PERMISSIONS_REQUEST_LOCATION = 1;

    TextView textView;

    Button button;

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

        textView = (TextView) findViewById(R.id.textView);

        button = (Button) findViewById(R.id.button);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (ContextCompat.checkSelfPermission(MainActivity.this,
                        Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
                            Manifest.permission.ACCESS_COARSE_LOCATION)) {
                        ActivityCompat.requestPermissions(MainActivity.this,
                                new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, MY_PERMISSIONS_REQUEST_LOCATION);
                    } else {
                        ActivityCompat.requestPermissions(MainActivity.this,
                                new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, MY_PERMISSIONS_REQUEST_LOCATION);
                    }
                } else {
                    LocationManager mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
                    Location location = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    try {
                        textView.setText(hereLocation(location.getLatitude(), location.getLongitude()));
                    } catch (Exception e) {
                        Toast.makeText(getApplicationContext(), "Not found!",
                                Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_LOCATION: {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    if (ContextCompat.checkSelfPermission(MainActivity.this,
                            Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {

                        LocationManager mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
                        Location location = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        try {
                            textView.setText(hereLocation(location.getLatitude(), location.getLongitude()));
                        } catch (Exception e) {
                            Toast.makeText(getApplicationContext(), "Not found!",
                                    Toast.LENGTH_SHORT).show();
                        }

                    }
                } else {
                    Toast.makeText(MainActivity.this, "No permission granted!", Toast.LENGTH_SHORT).show();
                }
                return;
            }
        }
    }

    public String hereLocation(double lat, double lng) {
        String cur_city_name = "";

        Geocoder gcd = new Geocoder(MainActivity.this,
                Locale.getDefault());
        List<Address> addresses;
        try {
            addresses = gcd.getFromLocation(lat, lng, 1);
            if (addresses.size() > 0)
                cur_city_name = addresses.get(0).getLocality();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Toast.makeText(this, "" + cur_city_name, Toast.LENGTH_SHORT).show();
        return cur_city_name;
    }


}

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout        
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">


    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Button"/>

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
</LinearLayout>

Solution

  • Try this it works perfect

     public String getAddress(double lats, double lons) {
    
                    Geocoder geocoder;
                    double lat = lats;
                    double lon = lons;
                    geocoder = new Geocoder(YourActivityName.this, Locale.getDefault());
                    List<android.location.Address> addresses = null;
                    try {
                        addresses = geocoder.getFromLocation(lat, lon, 1);
                    } catch (IOException e) {
    
                        e.printStackTrace();
                    }
    
                    if (addresses != null) {
    
                        String address = addresses.get(0).getAddressLine(0); 
                        String city = addresses.get(0).getLocality();
                        String state = addresses.get(0).getAdminArea();
                        String country = addresses.get(0).getCountryName();
                        String postalCode = addresses.get(0).getPostalCode();
                        String knownName = addresses.get(0).getFeatureName(); 
    
                        return address;
                    } else {
                        return "failed";
                    }
    
    
                }