-2

I'm developping an application with Android Studio in Java. I have a problem. I work with Google Map. I have created a circle but I don't know how I can detect if the location of the person is in the circle. I have found something to check that but it doesn't work, my application crash instantly. Thank's for your help.

The code that I found :

        float[] distance = new float[2];

        Location.distanceBetween(currentLocation.getLatitude(), currentLocation.getLongitude(), circle.getCenter().latitude,circle.getCenter().longitude,distance);
        if ( distance[0] <= circle.getRadius())
        {
            // Inside The Circle
        }
        else
        {
            // Outside The Circle
        }

And this is all my code (without the imports lines) :

public class MainActivity extends FragmentActivity implements OnMapReadyCallback, LocationListener {

    Location currentLocation;
    FusedLocationProviderClient fusedLocationProviderClient;
    private static final int REQUEST_CODE = 101;
    private Handler mHandler = new Handler();
    private  TextView mTextViewResult;

    private GoogleMap mMap;
    private Marker markertest;
    double lat;
    double longi;
    boolean zoom;

    float[] distance = new float[2];
    Circle circle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        zoom = true;
        fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
        mTextViewResult = findViewById(R.id.text_view_result);
        //openActivite();
        fetchLastLocation();
        Check();
        runnabletest.run();
    }

    public void Check(){
        currentLocation.distanceBetween(currentLocation.getLatitude(), currentLocation.getLongitude(), circle.getCenter().latitude,circle.getCenter().longitude,distance);
        if ( distance[0] <= circle.getRadius())
        {
            System.exit(0);
        }
        else
        {
            // Outside The Circle
        }
    }

    private Runnable runnabletest = new Runnable(){
        @Override
        public void run() {
            fetchLastLocation();
            mHandler.postDelayed(runnabletest, 10000);
        }
    };


    private void fetchLastLocation(){
        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(this, new String[]
                    {Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE);
            return;
        }
    Task<Location> task = fusedLocationProviderClient.getLastLocation();
        task.addOnSuccessListener(new OnSuccessListener<Location>() {
            @Override
            public void onSuccess(Location location) {
                if(location != null){
                    currentLocation = location;
                    Toast.makeText(getApplicationContext(), currentLocation.getLatitude()
                    +""+currentLocation.getLongitude(), Toast.LENGTH_SHORT).show();
                    SupportMapFragment supportMapFragment = (SupportMapFragment)
                            getSupportFragmentManager().findFragmentById(R.id.google_map);
                    supportMapFragment.getMapAsync(MainActivity.this);
                    lat = currentLocation.getLatitude();
                    longi = currentLocation.getLongitude();
                }
            }
        });
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        LatLng latLng = new LatLng(lat, longi);
        MarkerOptions markerOptions = new MarkerOptions().position(latLng).title("Vous");
        googleMap.addMarker(markerOptions);
        LatLng latLng2 = new LatLng(48.8534, 2.3488);
        MarkerOptions markerOptions2 = new MarkerOptions().position(latLng2).title("Point d'arrivée").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
        googleMap.addMarker(markerOptions2);
        circle = googleMap.addCircle(new CircleOptions().center(latLng2).radius(500.0).strokeWidth(3f).strokeColor(Color.BLUE).fillColor(Color.argb(70, 150, 50, 50)));
        if(zoom == true){
            googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
            googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 5));
            googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng2));
            googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng2, 5));
        }
        zoom = false;
    }

    @Override
    public void onLocationChanged(Location currentLocation){

    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch(requestCode){
            case REQUEST_CODE:
                if(grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                    fetchLastLocation();;
                }
                break;
        }
    }

}

And the errors in the logs :

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.okiep, PID: 21205
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.okiep/com.example.okiep.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
        at android.app.ActivityThread.-wrap12(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6119)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference
        at com.example.okiep.MainActivity.Check(MainActivity.java:81)
        at com.example.okiep.MainActivity.onCreate(MainActivity.java:76)
        at android.app.Activity.performCreate(Activity.java:6679)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726) 
        at android.app.ActivityThread.-wrap12(ActivityThread.java) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477) 
        at android.os.Handler.dispatchMessage(Handler.java:102) 
        at android.os.Looper.loop(Looper.java:154) 
        at android.app.ActivityThread.main(ActivityThread.java:6119) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776) 
Snweyzer
  • 1
  • 1
  • 1
    When the application crashes, are there any error messages? Please post any logs that you have so that we can help you better. – wxker Apr 21 '20 at 01:26
  • I have answered you just under. Thank's :) – Snweyzer Apr 22 '20 at 15:20
  • 1
    [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Dour High Arch May 05 '21 at 23:08

1 Answers1

0

The error message says that you have a NullPointerException where the null value is currentLocation. This means at the point where it is called on line 81 in the Check method, it has a null value. Looking at the sequence of execution, it seems like the right place to put your call to the Check method should be inside the onSuccess callback within fetchLastLocation.

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        zoom = true;
        fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
        mTextViewResult = findViewById(R.id.text_view_result);
        //openActivite();
        runnabletest.run();
    }

    private void fetchLastLocation(){
        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(this, new String[]
                    {Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE);
            return;
        }
    Task<Location> task = fusedLocationProviderClient.getLastLocation();
        task.addOnSuccessListener(new OnSuccessListener<Location>() {
            @Override
            public void onSuccess(Location location) {
                if(location != null){
                    currentLocation = location;
                    Toast.makeText(getApplicationContext(), currentLocation.getLatitude()
                    +""+currentLocation.getLongitude(), Toast.LENGTH_SHORT).show();
                    SupportMapFragment supportMapFragment = (SupportMapFragment)
                            getSupportFragmentManager().findFragmentById(R.id.google_map);
                    supportMapFragment.getMapAsync(MainActivity.this);
                    lat = currentLocation.getLatitude();
                    longi = currentLocation.getLongitude();
                    Check(); // Call the Check method here
                }
            }
        });
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        LatLng latLng = new LatLng(lat, longi);
        MarkerOptions markerOptions = new MarkerOptions().position(latLng).title("Vous");
        googleMap.addMarker(markerOptions);
        LatLng latLng2 = new LatLng(48.8534, 2.3488);
        MarkerOptions markerOptions2 = new MarkerOptions().position(latLng2).title("Point d'arrivée").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
        googleMap.addMarker(markerOptions2);
        circle = googleMap.addCircle(new CircleOptions().center(latLng2).radius(500.0).strokeWidth(3f).strokeColor(Color.BLUE).fillColor(Color.argb(70, 150, 50, 50)));
        if(zoom == true){
            googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
            googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 5));
            googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng2));
            googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng2, 5));
        }
        zoom = false;
        fetchLastLocation(); //move fetchLastLocation to here
    }

Also, by java convention, method names should be camelcase. Your Check method should start with a lower case letter.

wxker
  • 1,234
  • 3
  • 9
  • Thank you very much for your answer ! I will try and I will tell you. – Snweyzer Apr 26 '20 at 12:20
  • I put the code inside the onSuccess but it crash instanly. What do you think ? Thank's :) – Snweyzer Apr 27 '20 at 23:24
  • Going to need more information. What is the error message? Please update your question with any logs you have. – wxker Apr 28 '20 at 00:21
  • @Snweyzer That error means that `circle` is null at the point where it is called in `Check`. Shift `fetchLastLocation` into `onMapReady`. I have edited my answer to reflect this. Please update the question with the error message you had in your last comment. – wxker May 03 '20 at 01:18
  • Thank's bro I succeed thank to your help ! <3 I close this post, thank's again ! – Snweyzer May 05 '20 at 17:02