Google地图在位置更新上返回null(Google Maps returns null on location update)

编程入门 行业动态 更新时间:2024-10-27 18:24:44
Google地图在位置更新上返回null(Google Maps returns null on location update)

几周来,当程序试图在地图上放置一个标记时,我得到了空指针异常。 我不知道为什么,我尝试了几个解决方案,但他们没有工作。 我在几台设备上遇到此错误。 例如,在100个设备上没有错误,但在5个或更多设备中发生此错误。 另外我无法使用.getMap()函数。 只有getMapAsync可用。

这是我从Firebase获得的错误:

Fatal Exception: java.lang.NullPointerException Attempt to invoke virtual method 'void com.google.android.gms.maps.GoogleMap.animateCamera(com.google.android.gms.maps.CameraUpdate)' on a null object reference

以下是Google地图片段:

<fragment xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/map1" class="com.google.android.gms.maps.SupportMapFragment" android:name="com.google.android.gms.maps.SupportMapFragment" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.ahmetbesli.eczanem.MapsActivityPicker" />

这是我的程序的代码:

public class MapsActivityPicker extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, View.OnClickListener { SharedPreferences sharedPreferences; GoogleMap mGoogleMap; SupportMapFragment mapFrag; LocationRequest mLocationRequest; GoogleApiClient mGoogleApiClient; Location mLastLocation; Marker mCurrLocationMarker; FusedLocationProviderClient mFusedLocationClient; LocationManager mLocationManager; ArrayList<MarkerData> markers = new ArrayList<>(); int counter = 1; int resumeCounter = 2; boolean add = true; LatLng midLatLng; LatLng latLngMaps; ImageView direction; ImageView bullet; ImageView share; ImageView nearMe; ImageView call; CountDownTimer timer; String pharmacyName; String pharmacyAddress; String markerPhone = null; Double markerLatitude; Double markerLongitude; private InterstitialAd mInterstitialAd; String shortURL; LocationCallback mLocationCallback; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_maps_picker); mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this); mapFrag = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map1); buildGoogleApiClient(); mapFrag.getMapAsync(this); mLocationManager = (LocationManager) MapsActivityPicker.this .getSystemService(Context.LOCATION_SERVICE); direction = findViewById(R.id.directionPicker); bullet = findViewById(R.id.bulletPicker); share = findViewById(R.id.sharePicker); nearMe = findViewById(R.id.accessPicker); call = findViewById(R.id.callPicker); direction.setOnClickListener(this); bullet.setOnClickListener(this); share.setOnClickListener(this); nearMe.setOnClickListener(this); call.setOnClickListener(this); sharedPreferences = this.getApplication().getSharedPreferences(Config.app_name,MODE_PRIVATE); mInterstitialAd = new InterstitialAd(this); mInterstitialAd.setAdUnitId("xxxxxxxxxx"); mInterstitialAd.loadAd(new AdRequest.Builder().build()); timer = new CountDownTimer(5000, 1000) { public void onTick(long millisUntilFinished) { } public void onFinish() { if (add) { if (mInterstitialAd != null) { if (mInterstitialAd.isLoaded()) { mInterstitialAd.show(); } } } } }; timer.start(); } @Override public void onPause() { super.onPause(); if (mFusedLocationClient != null) { mFusedLocationClient.removeLocationUpdates(mLocationCallback); } } @Override public void onMapReady(final GoogleMap googleMap) { mGoogleMap = googleMap; mGoogleMap.getUiSettings().setMapToolbarEnabled(false); mGoogleMap.setInfoWindowAdapter(new CustomInfoWindowAdapter(MapsActivityPicker.this)); mGoogleMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() { public void onMapClick(LatLng latLng) { bullet.setVisibility(View.VISIBLE); share.setVisibility(View.GONE); direction.setVisibility(View.GONE); nearMe.setVisibility(View.VISIBLE); call.setVisibility(View.GONE); } }); mGoogleMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() { @Override public void onInfoWindowClick(Marker marker) { Intent intent = new Intent(MapsActivityPicker.this, HomePageShared.class); intent.putExtra("name",marker.getTitle()); intent.putExtra("address",marker.getSnippet()); intent.putExtra("phone",markerPhone); intent.putExtra("latitude",marker.getPosition().latitude); intent.putExtra("longitude",marker.getPosition().longitude); intent.putExtra("userLatitude", midLatLng.latitude); intent.putExtra("userLongitude",midLatLng.longitude); startActivity(intent); } }); mGoogleMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() { Marker currentShown; @Override public boolean onMarkerClick(Marker marker) { if (marker.equals(currentShown)) { marker.hideInfoWindow(); currentShown = null; } else { marker.showInfoWindow(); currentShown = marker; } pharmacyName = marker.getTitle(); pharmacyAddress = marker.getSnippet(); markerLatitude = marker.getPosition().latitude; markerLongitude = marker.getPosition().longitude; for(int i = 0; i < markers.size(); i++){ if(markers.get(i).getName().equals(pharmacyName)){ markerPhone = markers.get(i).getPhone(); } } shortURL = "http://maps.google.com/maps?daddr=" + markerLatitude + "," + markerLongitude; latLngMaps = marker.getPosition(); share.setVisibility(View.VISIBLE); direction.setVisibility(View.VISIBLE); bullet.setVisibility(View.GONE); nearMe.setVisibility(View.GONE); call.setVisibility(View.VISIBLE); return true; } }); googleMap.setOnCameraIdleListener(new GoogleMap.OnCameraIdleListener() { @Override public void onCameraIdle() { //get latlng at the center by calling midLatLng = googleMap.getCameraPosition().target; //request(); requestRetrofit(); googleMap.clear(); } }); if(sharedPreferences.getBoolean(Config.theme,false)){ mGoogleMap.setMapStyle(MapStyleOptions.loadRawResourceStyle(this, R.raw.night_mode)); } } protected void getGPS() { AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder( this); alertDialogBuilder .setMessage("Konum Servisiniz kapalı. Eczaneleri görebilmek için lütfen açınız.") .setCancelable(false) .setPositiveButton("Konum Servisini Aç", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { Intent callGPSSettingIntent = new Intent( android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS); MapsActivityPicker.this.startActivity(callGPSSettingIntent); } }); alertDialogBuilder.setNegativeButton("Kapalı Kalsın", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); AlertDialog alert = alertDialogBuilder.create(); alert.show(); } public void requestRetrofit(){ ApiInterface apiInterface = ApiClient.getRetrofit().create(ApiInterface.class); Call<ArrayList<Eczane>> call = apiInterface.getPharmacies(new com.ahmetbesli.eczanem.Request(String.valueOf(midLatLng.latitude),String.valueOf(midLatLng.longitude))); call.enqueue(new Callback<ArrayList<Eczane>>() { @Override public void onResponse(Call<ArrayList<Eczane>> call, retrofit2.Response<ArrayList<Eczane>> response) { markers.clear(); if (response.body().get(0) != null) { for (int i = 0; i < 5; i++) { if (!response.body().get(i).getLatitude().equals("undefined") && !response.body().get(i).getLongitude().equals("undefined") && !response.body().get(i).getLatitude().equals("") && !response.body().get(i).getLongitude().equals("")) { createMarker(Double.valueOf(response.body().get(i).getLatitude()), Double.valueOf(response.body().get(i).getLongitude()), response.body().get(i).getName(), response.body().get(i).getAdress(), response.body().get(i).getPhone(), R.mipmap.marker); } } } } @Override public void onFailure(Call<ArrayList<Eczane>> call, Throwable t) { } }); } protected void starter() { //Initialize Google Play Services if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { //Location Permission already granted buildGoogleApiClient(); } else { //Request Location Permission checkLocationPermission(); } } else { buildGoogleApiClient(); } } protected synchronized void buildGoogleApiClient() { mGoogleApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(LocationServices.API) .build(); mGoogleApiClient.connect(); } @Override public void onConnected(Bundle bundle) { mLocationRequest = LocationRequest.create(); mLocationRequest.setInterval(120000); // two minute interval mLocationRequest.setFastestInterval(120000); mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY); if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper()); } } @Override public void onConnectionSuspended(int i) { } @Override public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { } public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99; private void checkLocationPermission() { if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // Should we show an explanation? if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) { // Show an explanation to the user *asynchronously* -- don't block // this thread waiting for the user's response! After the user // sees the explanation, try again to request the permission. new AlertDialog.Builder(this) .setTitle("Konum Servisi için izin gerekli.") .setMessage("Bu uygulama konum servisi iznine ihtiyaç duymaktadır. Lütfen kabul ediniz.") .setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { //Prompt the user once explanation has been shown ActivityCompat.requestPermissions(MapsActivityPicker.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSIONS_REQUEST_LOCATION); } }) .create() .show(); } else { // No explanation needed, we can request the permission. ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSIONS_REQUEST_LOCATION); } } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) { switch (requestCode) { case MY_PERMISSIONS_REQUEST_LOCATION: { // If request is cancelled, the result arrays are empty. if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // permission was granted, yay! Do the // location-related task you need to do. if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { if (mGoogleApiClient == null) { buildGoogleApiClient(); } } } else { // permission denied, boo! Disable the // functionality that depends on this permission. Toast.makeText(this, "İzin Reddedildi", Toast.LENGTH_LONG).show(); } } // other 'case' lines to check for other // permissions this app might request } } @Override public void onResume() { super.onResume(); if (resumeCounter <= 2) { starter(); resumeCounter++; } if (counter == 0) { if (mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { starter(); counter++; } else { getGPS(); counter++; } } } protected void createMarker(double latitude, double longitude, String title, String snippet, String phone, int iconResID) { MarkerData marker = new MarkerData(title, snippet, phone, latitude, longitude); markers.add(marker); mGoogleMap.addMarker(new MarkerOptions() .position(new LatLng(latitude, longitude)) .anchor(0.5f, 0.5f) .title(title) .snippet(snippet) .icon(BitmapDescriptorFactory.fromResource(iconResID))); } @Override protected void onStart(){ super.onStart(); mLocationCallback = new LocationCallback() { @Override public void onLocationResult(LocationResult locationResult) { for (Location location : locationResult.getLocations()) { mLastLocation = location; if (mCurrLocationMarker != null) { mCurrLocationMarker.remove(); } mGoogleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), 10.7f)); } } }; } }

For weeks I'm getting null pointer exception, when the program tries to put a marker on the map. I don't know why, I tried couple of solutions, but they did not work. I am getting this error on several devices. For instance, there is no error on 100 devices but in 5 or more devices this error is being occured. Also I am not able to use .getMap() function. There is just getMapAsync available.

Here is the error that I obtain from Firebase:

Fatal Exception: java.lang.NullPointerException Attempt to invoke virtual method 'void com.google.android.gms.maps.GoogleMap.animateCamera(com.google.android.gms.maps.CameraUpdate)' on a null object reference

Here is the Google Maps fragment:

<fragment xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/map1" class="com.google.android.gms.maps.SupportMapFragment" android:name="com.google.android.gms.maps.SupportMapFragment" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.ahmetbesli.eczanem.MapsActivityPicker" />

Here is the code of my program:

public class MapsActivityPicker extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, View.OnClickListener { SharedPreferences sharedPreferences; GoogleMap mGoogleMap; SupportMapFragment mapFrag; LocationRequest mLocationRequest; GoogleApiClient mGoogleApiClient; Location mLastLocation; Marker mCurrLocationMarker; FusedLocationProviderClient mFusedLocationClient; LocationManager mLocationManager; ArrayList<MarkerData> markers = new ArrayList<>(); int counter = 1; int resumeCounter = 2; boolean add = true; LatLng midLatLng; LatLng latLngMaps; ImageView direction; ImageView bullet; ImageView share; ImageView nearMe; ImageView call; CountDownTimer timer; String pharmacyName; String pharmacyAddress; String markerPhone = null; Double markerLatitude; Double markerLongitude; private InterstitialAd mInterstitialAd; String shortURL; LocationCallback mLocationCallback; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_maps_picker); mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this); mapFrag = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map1); buildGoogleApiClient(); mapFrag.getMapAsync(this); mLocationManager = (LocationManager) MapsActivityPicker.this .getSystemService(Context.LOCATION_SERVICE); direction = findViewById(R.id.directionPicker); bullet = findViewById(R.id.bulletPicker); share = findViewById(R.id.sharePicker); nearMe = findViewById(R.id.accessPicker); call = findViewById(R.id.callPicker); direction.setOnClickListener(this); bullet.setOnClickListener(this); share.setOnClickListener(this); nearMe.setOnClickListener(this); call.setOnClickListener(this); sharedPreferences = this.getApplication().getSharedPreferences(Config.app_name,MODE_PRIVATE); mInterstitialAd = new InterstitialAd(this); mInterstitialAd.setAdUnitId("xxxxxxxxxx"); mInterstitialAd.loadAd(new AdRequest.Builder().build()); timer = new CountDownTimer(5000, 1000) { public void onTick(long millisUntilFinished) { } public void onFinish() { if (add) { if (mInterstitialAd != null) { if (mInterstitialAd.isLoaded()) { mInterstitialAd.show(); } } } } }; timer.start(); } @Override public void onPause() { super.onPause(); if (mFusedLocationClient != null) { mFusedLocationClient.removeLocationUpdates(mLocationCallback); } } @Override public void onMapReady(final GoogleMap googleMap) { mGoogleMap = googleMap; mGoogleMap.getUiSettings().setMapToolbarEnabled(false); mGoogleMap.setInfoWindowAdapter(new CustomInfoWindowAdapter(MapsActivityPicker.this)); mGoogleMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() { public void onMapClick(LatLng latLng) { bullet.setVisibility(View.VISIBLE); share.setVisibility(View.GONE); direction.setVisibility(View.GONE); nearMe.setVisibility(View.VISIBLE); call.setVisibility(View.GONE); } }); mGoogleMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() { @Override public void onInfoWindowClick(Marker marker) { Intent intent = new Intent(MapsActivityPicker.this, HomePageShared.class); intent.putExtra("name",marker.getTitle()); intent.putExtra("address",marker.getSnippet()); intent.putExtra("phone",markerPhone); intent.putExtra("latitude",marker.getPosition().latitude); intent.putExtra("longitude",marker.getPosition().longitude); intent.putExtra("userLatitude", midLatLng.latitude); intent.putExtra("userLongitude",midLatLng.longitude); startActivity(intent); } }); mGoogleMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() { Marker currentShown; @Override public boolean onMarkerClick(Marker marker) { if (marker.equals(currentShown)) { marker.hideInfoWindow(); currentShown = null; } else { marker.showInfoWindow(); currentShown = marker; } pharmacyName = marker.getTitle(); pharmacyAddress = marker.getSnippet(); markerLatitude = marker.getPosition().latitude; markerLongitude = marker.getPosition().longitude; for(int i = 0; i < markers.size(); i++){ if(markers.get(i).getName().equals(pharmacyName)){ markerPhone = markers.get(i).getPhone(); } } shortURL = "http://maps.google.com/maps?daddr=" + markerLatitude + "," + markerLongitude; latLngMaps = marker.getPosition(); share.setVisibility(View.VISIBLE); direction.setVisibility(View.VISIBLE); bullet.setVisibility(View.GONE); nearMe.setVisibility(View.GONE); call.setVisibility(View.VISIBLE); return true; } }); googleMap.setOnCameraIdleListener(new GoogleMap.OnCameraIdleListener() { @Override public void onCameraIdle() { //get latlng at the center by calling midLatLng = googleMap.getCameraPosition().target; //request(); requestRetrofit(); googleMap.clear(); } }); if(sharedPreferences.getBoolean(Config.theme,false)){ mGoogleMap.setMapStyle(MapStyleOptions.loadRawResourceStyle(this, R.raw.night_mode)); } } protected void getGPS() { AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder( this); alertDialogBuilder .setMessage("Konum Servisiniz kapalı. Eczaneleri görebilmek için lütfen açınız.") .setCancelable(false) .setPositiveButton("Konum Servisini Aç", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { Intent callGPSSettingIntent = new Intent( android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS); MapsActivityPicker.this.startActivity(callGPSSettingIntent); } }); alertDialogBuilder.setNegativeButton("Kapalı Kalsın", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); AlertDialog alert = alertDialogBuilder.create(); alert.show(); } public void requestRetrofit(){ ApiInterface apiInterface = ApiClient.getRetrofit().create(ApiInterface.class); Call<ArrayList<Eczane>> call = apiInterface.getPharmacies(new com.ahmetbesli.eczanem.Request(String.valueOf(midLatLng.latitude),String.valueOf(midLatLng.longitude))); call.enqueue(new Callback<ArrayList<Eczane>>() { @Override public void onResponse(Call<ArrayList<Eczane>> call, retrofit2.Response<ArrayList<Eczane>> response) { markers.clear(); if (response.body().get(0) != null) { for (int i = 0; i < 5; i++) { if (!response.body().get(i).getLatitude().equals("undefined") && !response.body().get(i).getLongitude().equals("undefined") && !response.body().get(i).getLatitude().equals("") && !response.body().get(i).getLongitude().equals("")) { createMarker(Double.valueOf(response.body().get(i).getLatitude()), Double.valueOf(response.body().get(i).getLongitude()), response.body().get(i).getName(), response.body().get(i).getAdress(), response.body().get(i).getPhone(), R.mipmap.marker); } } } } @Override public void onFailure(Call<ArrayList<Eczane>> call, Throwable t) { } }); } protected void starter() { //Initialize Google Play Services if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { //Location Permission already granted buildGoogleApiClient(); } else { //Request Location Permission checkLocationPermission(); } } else { buildGoogleApiClient(); } } protected synchronized void buildGoogleApiClient() { mGoogleApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(LocationServices.API) .build(); mGoogleApiClient.connect(); } @Override public void onConnected(Bundle bundle) { mLocationRequest = LocationRequest.create(); mLocationRequest.setInterval(120000); // two minute interval mLocationRequest.setFastestInterval(120000); mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY); if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper()); } } @Override public void onConnectionSuspended(int i) { } @Override public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { } public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99; private void checkLocationPermission() { if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // Should we show an explanation? if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) { // Show an explanation to the user *asynchronously* -- don't block // this thread waiting for the user's response! After the user // sees the explanation, try again to request the permission. new AlertDialog.Builder(this) .setTitle("Konum Servisi için izin gerekli.") .setMessage("Bu uygulama konum servisi iznine ihtiyaç duymaktadır. Lütfen kabul ediniz.") .setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { //Prompt the user once explanation has been shown ActivityCompat.requestPermissions(MapsActivityPicker.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSIONS_REQUEST_LOCATION); } }) .create() .show(); } else { // No explanation needed, we can request the permission. ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSIONS_REQUEST_LOCATION); } } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) { switch (requestCode) { case MY_PERMISSIONS_REQUEST_LOCATION: { // If request is cancelled, the result arrays are empty. if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // permission was granted, yay! Do the // location-related task you need to do. if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { if (mGoogleApiClient == null) { buildGoogleApiClient(); } } } else { // permission denied, boo! Disable the // functionality that depends on this permission. Toast.makeText(this, "İzin Reddedildi", Toast.LENGTH_LONG).show(); } } // other 'case' lines to check for other // permissions this app might request } } @Override public void onResume() { super.onResume(); if (resumeCounter <= 2) { starter(); resumeCounter++; } if (counter == 0) { if (mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { starter(); counter++; } else { getGPS(); counter++; } } } protected void createMarker(double latitude, double longitude, String title, String snippet, String phone, int iconResID) { MarkerData marker = new MarkerData(title, snippet, phone, latitude, longitude); markers.add(marker); mGoogleMap.addMarker(new MarkerOptions() .position(new LatLng(latitude, longitude)) .anchor(0.5f, 0.5f) .title(title) .snippet(snippet) .icon(BitmapDescriptorFactory.fromResource(iconResID))); } @Override protected void onStart(){ super.onStart(); mLocationCallback = new LocationCallback() { @Override public void onLocationResult(LocationResult locationResult) { for (Location location : locationResult.getLocations()) { mLastLocation = location; if (mCurrLocationMarker != null) { mCurrLocationMarker.remove(); } mGoogleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), 10.7f)); } } }; } }

最满意答案

在您的onStart方法中,您可能在未分配时调用mGoogleMap.animateCamera() 。 它正在onMapReady中分配,您需要检查它是否为空。

if(mGoogleMap != null){ mGoogleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), 10.7f)); }

我怀疑你有竞争条件:在onMapReady()之前,在某些设备上onMapReady()方法...所以一切工作正常。 但在其他设备上onLocationResult()在onMapReady()方法之前调用,因此mGoogleMap为null ! 因此,您必须检查是否已分配“mGoogleMap”。

改为:

//create a class variable mLatLng private LatLng mLatLng;

现在更改onLocationResult()方法中的代码,如下所示:

public void onLocationResult(LocationResult locationResult) { for (Location location : locationResult.getLocations()) { mLastLocation = location; if (mCurrLocationMarker != null) { mCurrLocationMarker.remove(); } mLatLng = new LatLng(location.getLatitude(), location.getLongitude()); moveMapTo(); }

添加方法:

private void moveMapTo(){ if(mLatLng == null) return; if(mGoogleMap != null){ mGoogleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 10.7f)); } }

在onMapReady()方法中,您只需添加:

moveMapTo();

在onLocationResult()之前调用onMapReady() ,变量“mLatLng”被定义并且有效,但是“mGoogleMap”为空 - 这会导致错误。 只要在onMapReady()正确定义了“mGoogleMap”, onMapReady() moveMapTo()再次被调用,并且您的动画会显示在正确的位置。 但是,如果在onLocationResult()之前调用了onLocationResult()则已经分配了“mGoogleMap”,并且在onLocationResult()一切按预期运行。

In your onStart method you are calling mGoogleMap.animateCamera() probably at a time when it is not assigned. It is being assigned in onMapReady you need to check to see if it is null.

if(mGoogleMap != null){ mGoogleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), 10.7f)); }

I suspect that you have a race condition: on some devices the onMapReady() method is being called before onLocationResult()...so everything works fine. But on other devices onLocationResult() is called before the onMapReady() method and therefore mGoogleMap is null! Therefore, you must check to see if "mGoogleMap" has been assigned.

Do this instead:

//create a class variable mLatLng private LatLng mLatLng;

Now change the code in your onLocationResult() method to look like this:

public void onLocationResult(LocationResult locationResult) { for (Location location : locationResult.getLocations()) { mLastLocation = location; if (mCurrLocationMarker != null) { mCurrLocationMarker.remove(); } mLatLng = new LatLng(location.getLatitude(), location.getLongitude()); moveMapTo(); }

Add the method:

private void moveMapTo(){ if(mLatLng == null) return; if(mGoogleMap != null){ mGoogleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 10.7f)); } }

And in onMapReady() method all you need is to add:

moveMapTo();

This way when onLocationResult() is called before onMapReady() the variable "mLatLng" is defined and valid, but "mGoogleMap" is null--which would cause an error. As soon as "mGoogleMap" is properly defined in onMapReady() moveMapTo() is called again and your animate to the proper location. If, however, onMapReady() is called before onLocationResult() then "mGoogleMap" is already assigned and in onLocationResult() everything works as intended.

更多推荐

本文发布于:2023-08-07 15:22:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1464917.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:新上   位置   地图   Google   null

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!