0

I am trying to take latitude and longitude from GPS

I found these links:

How to get Android GPS location

https://www.vogella.com/tutorials/AndroidLocationAPI/article.html

And this is my code:

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;

import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements LocationListener {
    private TextView latituteField;
    private TextView longitudeField;
    private LocationManager locationManager;
    private String provider;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        latituteField = (TextView) findViewById(R.id.TextView02);
        longitudeField = (TextView) findViewById(R.id.TextView04);

        // Get the location manager
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        // Define the criteria how to select the locatioin provider -> use
        // default
        Criteria criteria = new Criteria();
        provider = locationManager.getBestProvider(criteria, false);

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_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.
            Location location = locationManager.getLastKnownLocation(provider);
            if (location != null) {
                System.out.println("Provider " + provider + " has been selected.");
                onLocationChanged(location);
            } else {
                latituteField.setText("Location not available");
                longitudeField.setText("Location not available");
            }
            return;
        }



    }


    @Override
    protected void onResume() {
        super.onResume();

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_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.
            locationManager.requestLocationUpdates(provider, 400, 1, this);
            return;
        }

    }
    @Override
    protected void onPause() {
        super.onPause();
        locationManager.removeUpdates(this);
    }
    @Override
    public void onLocationChanged(Location location) {
        double lat = (double) (location.getLatitude());
        double lng = (double) (location.getLongitude());
        latituteField.setText(String.valueOf(lat));
        longitudeField.setText(String.valueOf(lng));
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Override
    public void onProviderEnabled(String provider) {
        Toast.makeText(this, "Enabled new provider " + provider,
                Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onProviderDisabled(String provider) {
        Toast.makeText(this, "Disabled provider " + provider,
                Toast.LENGTH_SHORT).show();
    }}

When I run this app, the app stop

This is the error:

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.locationmanagertutorial, PID: 13737
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.locationmanagertutorial/com.example.locationmanagertutorial.MainActivity}: java.lang.IllegalArgumentException: invalid provider: null
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2957)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3032)
        at android.app.ActivityThread.-wrap11(Unknown Source:0)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1696)
        at android.os.Handler.dispatchMessage(Handler.java:105)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6944)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
     Caused by: java.lang.IllegalArgumentException: invalid provider: null
        at android.location.LocationManager.checkProvider(LocationManager.java:2098)
        at android.location.LocationManager.getLastKnownLocation(LocationManager.java:1199)
        at com.example.locationmanagertutorial.MainActivity.onCreate(MainActivity.java:47)
        at android.app.Activity.performCreate(Activity.java:7183)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1220)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2910)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3032) 
        at android.app.ActivityThread.-wrap11(Unknown Source:0) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1696) 
        at android.os.Handler.dispatchMessage(Handler.java:105) 
        at android.os.Looper.loop(Looper.java:164) 
        at android.app.ActivityThread.main(ActivityThread.java:6944) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374) 

IF it is possible I want to get latitude and longitude from GPS without the internet.

ozan33.java
  • 33
  • 1
  • 7

2 Answers2

0

You should do location related queries after checking permission. Its better create another method for starting location service like

private void startLocationservice(){
    Criteria criteria = new Criteria();
    provider = locationManager.getBestProvider(criteria, false);
    if(provider == null){
       provider = LocationManager.GPS_PROVIDER;
    }
    locationManager.requestLocationUpdates(provider, 400, 1, this);
}

now in onCreate add this code

if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
    startLocationservice();
    }
 else{
   String [] missingPermissions = {Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION }; 
   ActivityCompat.requestPermissions(activity, missingPermissions, PERMISSIONS_REQUEST_CODE)
 }

add callback activity

public void onRequestPermissionsResult(int requestCode, int[] grantResults){
if (ActivityCompat.checkSelfPermission(this,    Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
    startLocationservice();
    }
 }

remove duplicate code from your activity

alokHarman
  • 289
  • 1
  • 8
-1
  1. Put following permission to android manifest (for LocationManager.GPS_PROVIDER) and request permission as usual using checkSelfPermission method.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="yourpackage.com">
    ...
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    ...
  1. Then you need request location updates as follow:
LocationManager locationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener();
try 
{
  if (locationManager != null) {
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 0, locationListener);
  }
} catch (Exception e) {
  //logger.error("Can't access GPS_PROVIDER", e);
}

  1. And here's LocationListener class:
private class LocationListener implements android.location.LocationListener {
        @Override
        public void onLocationChanged(Location location) {
            //logger.trace(String.format("Location changed: provider=%1$s, lat = %2$.4f, lon = %3$.4f, time = %4$tF %4$tT", location.getProvider(), location.getLatitude(), location.getLongitude(), new Date(location.getTime())));
        }

        @Override
        public void onProviderDisabled(String provider) {
//            logger.trace(provider + " disabled");
        }

        @Override
        public void onProviderEnabled(String provider) {
//            logger.trace(provider + " enabled");
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
//            logger.trace(provider + " sent changed to " + Integer.toString(status));
        }
    }
Dmitri
  • 24
  • 5