0

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>
Daniel
  • 2,355
  • 9
  • 23
  • 30
Drickuss Merguez
  • 49
  • 1
  • 1
  • 8
  • `mLocationManager.getLastKnownLocation()` returns last cached location, use `mLocationManager.requestLocationUpdates()` where you need to provide callback and in that callback you will receive latest location. – Akshay Bhat 'AB' Jan 03 '17 at 10:59
  • @Drickuss Merguez deleted my answer. I don't do a coding job here.We can show you want to do and you need to try it your self :) – Charuක Jan 03 '17 at 11:04

3 Answers3

1

refer the link

How to get city name from latitude and longitude coordinates in Google Maps?

Geocoder gcd = new Geocoder(context, Locale.getDefault());
List<Address> addresses = gcd.getFromLocation(lat, lng, 1);
if (addresses.size() > 0) 
{
    System.out.println(addresses.get(0).getLocality());
}
else
{
   // do your staff
}
Community
  • 1
  • 1
0

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";
                }


            }
0
        Geocoder geocoder;
    List<Address> addresses = new ArrayList<Address>();
    geocoder = new Geocoder(MapsActivity.this, Locale.getDefault());

    try {
        addresses = geocoder.getFromLocation(lati, longi, 1);
        // Here 1 represent max location result to returned, by documents it recommended 1 to 5
      //  addresses.add();
    } catch (IOException e) {
        e.printStackTrace();
    }
    if (!addresses.isEmpty()){
        address = addresses.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
        city = addresses.get(0).getLocality();
        state = addresses.get(0).getAdminArea();
        country = addresses.get(0).getCountryName();
        postalCode = addresses.get(0).getPostalCode();
    }
Nandu
  • 1
  • 3