I am trying to do the simple task of getting the current location of my device, however after some mind bending hours, I still can't seem to get it to work..
My MapFragment code:
package com.example.curroorbis_v0;
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapFragment extends Fragment implements OnMapReadyCallback, LocationListener {
private GoogleMap mMap;
private int TotalMarkers = 1;
public static MapFragment newInstance() {
MapFragment fragment = new MapFragment();
return fragment;
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_map, container, false);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) this.getChildFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
return view;
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
// Add a marker in Denmark and move the camera + zoom
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), 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.
ActivityCompat.requestPermissions(getActivity(),new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.INTERNET}, 0);
return;
}
// THIS MAKES IT WORK!!
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000 , 0, this);
locationManager.removeUpdates(this);
LatLng denmark = new LatLng(locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER).getLatitude(), locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER).getLongitude());
mMap.addMarker(new MarkerOptions().position(denmark).title("Marker at You"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(denmark));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(denmark, 15));
// Add custom markers
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
@Override
public void onMapClick(LatLng latLng) {
MarkerOptions waypoint = new MarkerOptions();
waypoint.position(latLng);
mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
waypoint.title("Waypoint " + TotalMarkers);
mMap.addMarker(waypoint);
//Logs lat/lng for each waypoint
Log.i("Waypoint", String.valueOf(waypoint.getPosition()));
TotalMarkers++;
}
});
}
@Override
public void onLocationChanged(Location location) {
Log.i("Message: ","Location changed, " + location.getAccuracy() + " , " + location.getLatitude()+ "," + location.getLongitude());
}
@Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
@Override
public void onProviderEnabled(String s) {
}
@Override
public void onProviderDisabled(String s) {
}
}
When I run this code on my samsung galaxy s8, I get the fatal error:
2020-06-16 21:42:00.247 31624-31624/com.example.curroorbis_v0 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.curroorbis_v0, PID: 31624
java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference
at com.example.curroorbis_v0.MapFragment.onMapReady(MapFragment.java:86)
at com.google.android.gms.maps.zzak.zza(Unknown Source:2)
at com.google.android.gms.maps.internal.zzaq.dispatchTransaction(Unknown Source:12)
at com.google.android.gms.internal.maps.zzb.onTransact(Unknown Source:12)
at android.os.Binder.transact(Binder.java:612)
at cx.b(:com.google.android.gms.dynamite_mapsdynamite@201817051@20.18.17 (040408-0):2)
at com.google.maps.api.android.lib6.impl.be.run(:com.google.android.gms.dynamite_mapsdynamite@201817051@20.18.17 (040408-0):2)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6938)
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)
And the app terminates.
To anyone who doesn't bother finding line 86, it is this piece of code:
LatLng denmark = new LatLng(locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER).getLatitude(), locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER).getLongitude());
If anyone has a clue to what might be going on, please don't hesitate.