Я пытаюсь сделать приложение для отслеживания местоположения Android. У меня проблема с location.addOnCompleteListener в getDeviceLocation () . Android-студия не проверяет это, и приложение вылетает здесь. Ниже приведен код, который я написал ...
import...
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
private GoogleMap mMap;
final int LOCATION_REQUEST_CODE = 1;
Location mLastLocation;
//FusedLocationProviderClient mFusedLocationClient;
LocationRequest mLocationRequest;
GoogleApiClient googleApiClient;
public static double longitude = 0.0d;
public static double latitude = 0.0d;
private FusedLocationProviderClient mFusedLocationProviderClient;
private long UPDATE_INTERVAL = 1000; /* 10 secs */
private long FASTEST_INTERVAL = 1000; /* 2 sec */
public static final String FINE_LOCATION = Manifest.permission.ACCESS_FINE_LOCATION;
public static final String COARSE_LOCATION = Manifest.permission.ACCESS_COARSE_LOCATION;
private static final int LOCATION_PERMISSION_REQUEST_CODE = 1234;
private boolean mLocationPermissionGranted = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
setupContents();
if (!isNetworkConnected()){
Toast.makeText(this, "You are offline!!!", Toast.LENGTH_SHORT).show();
finish();
return;
}
getLocationPermission();
//startLocationUpdates();
}
public void initMap() {
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
// mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
mapFragment.getMapAsync(this);
}
public void setupContents() {
btnEnd = findViewById(R.id.btnEnd);
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
Toast.makeText(this, "Map is ready", Toast.LENGTH_SHORT).show();
if (mLocationPermissionGranted) {
getDeviceLocation();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
return;
}
mMap.setMyLocationEnabled(true);
}
}
public void getLocationPermission(){
String [] permissions={Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION};
if(ContextCompat.checkSelfPermission(this.getApplicationContext(),FINE_LOCATION)
==PackageManager.PERMISSION_GRANTED){
if(ContextCompat.checkSelfPermission(this.getApplicationContext(),COARSE_LOCATION)
==PackageManager.PERMISSION_GRANTED){
mLocationPermissionGranted=true;
showGPSDisabledAlertToUser();
initMap();
} else {
ActivityCompat.requestPermissions(this,permissions,LOCATION_PERMISSION_REQUEST_CODE);
}
}
else {
ActivityCompat.requestPermissions(this,permissions,LOCATION_PERMISSION_REQUEST_CODE);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
mLocationPermissionGranted=false;
switch (requestCode){
case LOCATION_PERMISSION_REQUEST_CODE:{
if(grantResults.length>0){
for(int i=0;i<grantResults.length;i++){
if(grantResults[i]!=PackageManager.PERMISSION_GRANTED){
mLocationPermissionGranted=false;
return;
}
}
mLocationPermissionGranted=true;
showGPSDisabledAlertToUser();
initMap();
}
}
}
}
private void getDeviceLocation(){
mFusedLocationProviderClient=LocationServices.getFusedLocationProviderClient(this);
try {
if(mLocationPermissionGranted){
Task<Location> location=mFusedLocationProviderClient.getLastLocation();
location.addOnCompleteListener(this,new OnCompleteListener<Location>() {
@Override
public void onComplete(@NonNull Task task) {
if(task.isSuccessful()){
Location currentLocation= (Location) task.getResult();
moveCamera(new LatLng(currentLocation.getLatitude(),currentLocation.getLongitude()),12);
}
else
Toast.makeText(MapsActivity.this, "Unable to get current location", Toast.LENGTH_SHORT).show();
}
});
}
}catch (SecurityException ex){
}
}
private void moveCamera(LatLng latLng,float zoom){
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,zoom));
}
private void showGPSDisabledAlertToUser() {
final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE );
String locationProviders = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if ( !manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {
// Call your Alert message
Intent callGPSSettingIntent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(callGPSSettingIntent);
Toast.makeText(this, "Please turn on your location", Toast.LENGTH_SHORT).show();
}
else if (locationProviders == null || locationProviders.equals("")) {
startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
else
return;
}
@Override
public void onLocationChanged(Location location) {
mLastLocation = location;
/* LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(12));*/
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
mMap.addMarker(new MarkerOptions().position(latLng));
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
}
private boolean isNetworkConnected() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo() != null;
}
}
Проблема возникает во время отладки: исходный код не соответствует байтовому коду после выполнения этого оператора location.addOnCompleteListener (this, new OnCompleteListener () {.
Зависимости gradle:
implementation 'com.google.android.gms:play-services-maps:15.0.1'
implementation 'com.google.android.gms:play-services-vision:15.0.2'
implementation 'com.google.android.gms:play-services-location:15.0.1'
implementation 'com.google.android.gms:play-services-maps:15.0.1'
сообщения трассировки стека приведены ниже:
09-08 22:47:43.485 30955-30955/? E/Zygote: v2
09-08 22:47:43.487 30955-30955/? E/Zygote: accessInfo : 0
09-08 22:47:47.056 30955-30993/com.example.muzammil.maptestingproject E/cr_VariationsUtils: Failed reading seed file "/data/user/0/com.example.muzammil.maptestingproject/app_webview/variations_seed_new": /data/user/0/com.example.muzammil.maptestingproject/app_webview/variations_seed_new (No such file or directory)
09-08 22:47:58.366 30955-30955/com.example.muzammil.maptestingproject E/BoostFramework: BoostFramework() : Exception_1 = java.lang.ClassNotFoundException: Didn't find class "com.qualcomm.qti.Performance" on path: DexPathList[[],nativeLibraryDirectories=[/system/lib, /vendor/lib]]
09-08 22:48:14.641 30955-30955/com.example.muzammil.maptestingproject E/art: The String#value field is not present on Android versions >= 6.0
09-08 22:48:15.379 30955-30955/com.example.muzammil.maptestingproject E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.muzammil.maptestingproject, PID: 30955
java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference
at com.example.muzammil.maptestingproject.Activities.MapsActivity$3.onComplete(MapsActivity.java:222)
at com.google.android.gms.tasks.zzj.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6776)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1518)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408)
Если у вас есть решение, помогите, пожалуйста. Заранее спасибо