Problems with obtaining location in android studio

-1

Good afternoon friends I have a problem, Well I have been doing tests and I would like to know where I am failing, as I see when I do debugeo, location returns null and therefore can not return the get Altitude or any other property, I would like to know the error or if it is not that of location What can be? if I have the permissions in manifest and puej I have an emulator nexus 5x api21 android 5.0.2

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    this.btnSitios_Turisticos = (Button) findViewById(R.id.btn_sitios_turistico);

    this.btnSitios_Turisticos.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intento_abrir_mapsactivity = new Intent(MainActivity.this, MapsActivity1.class);
            startActivity(intento_abrir_mapsactivity);

        }
    });




    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

        ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.

           return;
        }
        LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        Toast.makeText(this
                ,"La latitud es:"+String.valueOf(location.getLatitude()),Toast.LENGTH_LONG).show();



    }





}

Here I have been doing a test but location is null when I do the debugeo thank you very much for the help.

    
asked by Ijsud 31.08.2018 в 19:58
source

2 answers

0

To get the location you have to do the following

first in the build gradle we import the play services location library

implementation 'com.google.android.gms:play-services-location:15.0.1'

We are going to use the FuseLocationProviderClient, for that we declare it

 private FusedLocationProviderClient mFusedLocationClient;

Then in onCreate() we initialize it

mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);

Ready, now the only thing that remains is to ask for the location, for that we will need

  • Ask for permissions
  • Get the location
  • We are going to create a method where first ask for the permissions and then get the location

        private void solicitarUbicacion(){
    private int MY_PERMISSIONS_REQUEST_READ_CONTACTS ;            
    //Permisos para FINE LOCATION
                if (ActivityCompat.checkSelfPermission(this,
                        Manifest.permission.ACCESS_FINE_LOCATION)
                        != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
                        != PackageManager.PERMISSION_GRANTED) {
    
                    ActivityCompat.requestPermissions(MainActivity.this,
                            new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                            MY_PERMISSIONS_REQUEST_READ_CONTACTS);
    
    
    
    
                        return;
                    }
                    //Obteniendo la ubicacion
                    mFusedLocationClient.getLastLocation()
                            .addOnSuccessListener(this, new OnSuccessListener<Location>() {
                                @Override
                                public void onSuccess(Location location) {
                                    //Sabiendo que obtuvimos location, lo usamos
                                    if (location != null) {
                                        Log.e("Latitud: ", +location.getLatitude() + "Longitud: " + location.getLongitude());
    
    
                                    }
                                }
                            });
                }
    

    This method you can call it inside the onCreate()

    solicitarUbicacion();
    

    With that you should work, do not forget to add your permissions to the manifest

     <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
        <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    

    Any questions you have made a video a month ago, I leave it in THIS link

        
    answered by 01.09.2018 / 00:08
    source
    1

    First you must define the necessary permissions in your AndroidManifest.xml

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    

    You have already defined the request for these permissions for devices with Android 6.0 or later, therefore this screen should be displayed:

    Something important, your Location service must be activated otherwise location will have a value null

    The 3 points above are necessary to obtain geolocation, but it is important to know that the provider you use may not obtain the data (you use only NETWORK_PROVIDER ), so suppliers are usually used GPS_PROVIDER or NETWORK_PROVIDER , since it may be that you are on a 4G network or on a WiFi network and with this we ensure you get the position.

    This would be the code:

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    
            ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
    
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.
    
                return;
            }
            LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
            Location location = null;
            LocationListener mlocListener = new LocationListener() {
                @Override
                public void onLocationChanged(Location location) {
    
                }
    
                @Override
                public void onStatusChanged(String provider, int status, Bundle extras) {
    
                }
    
                @Override
                public void onProviderEnabled(String provider) {
    
                }
    
                @Override
                public void onProviderDisabled(String provider) {
    
                }
            };
    
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
            if (locationManager != null) {
                //Existe GPS_PROVIDER obtiene ubicación
                location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            }
    
            if(location == null){ //Trata con NETWORK_PROVIDER
                locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, mlocListener);
                if (locationManager != null) {
                    //Existe NETWORK_PROVIDER obtiene ubicación
                    location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                }
            }
            if(location != null) {
                Toast.makeText(this, "La latitud es:" + location.getLatitude() + " la longitud es: " +location.getLongitude(), Toast.LENGTH_LONG).show();
            }else {
                Toast.makeText(this, "No se pudo obtener geolocalización", Toast.LENGTH_LONG).show();                
            }
    
        }
    

    In this way you can obtain your geolocation in an appropriate way.

        
    answered by 01.09.2018 в 01:35