Google 单击按钮时地图崩溃。 (无效 com.google.maps.api.android.lib6.impl.bp.v())

Google Maps crashing when clicking on the button. (void com.google.maps.api.android.lib6.impl.bp.v())

google 地图 activity 之前可以工作,但是当我尝试实现相机时 activity 它坏了,我已经恢复了更改,但它仍然坏了。

此应用程序崩溃并显示此错误:java.lang.NullPointerException:尝试在空对象引用上调用接口方法'void com.google.maps.api.android.lib6.impl.bp.v()'

Java 文件:

package com.example.recipeverse_app;

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

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.media.Image;
import android.net.Uri;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.provider.Settings;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.google.android.gms.common.api.GoogleApi;
import com.google.android.gms.common.api.GoogleApiClient;
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.MapView;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.karumi.dexter.Dexter;
import com.karumi.dexter.PermissionToken;
import com.karumi.dexter.listener.PermissionDeniedResponse;
import com.karumi.dexter.listener.PermissionGrantedResponse;
import com.karumi.dexter.listener.PermissionRequest;
import com.karumi.dexter.listener.single.PermissionListener;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

public class gMapsActivity extends AppCompatActivity implements OnMapReadyCallback {

    boolean PermissionGranted;
    MapView mapView;
    private GoogleMap mMap;
    EditText locationSearch;
    ImageView SearchIcon;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_g_maps);

        mapView = findViewById(R.id.googleMap);

        checkPermission();

        if (PermissionGranted) {
            mapView.getMapAsync(this);
            mapView.onCreate(savedInstanceState);
        }
    }

    private void checkPermission() {

        Dexter.withContext(this).withPermission(Manifest.permission.ACCESS_FINE_LOCATION).withListener(new PermissionListener() {
            @Override
            public void onPermissionGranted(PermissionGrantedResponse permissionGrantedResponse) {
                Toast.makeText(gMapsActivity.this, "Permission Granted", Toast.LENGTH_SHORT).show();
                PermissionGranted = true;
            }

            @Override
            public void onPermissionDenied(PermissionDeniedResponse permissionDeniedResponse) {
                Intent intent = new Intent();
                intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                Uri uri = Uri.fromParts("package", getPackageName(), "");
                intent.setData(uri);
                startActivity(intent);
            }

            @Override
            public void onPermissionRationaleShouldBeShown(PermissionRequest permissionRequest, PermissionToken permissionToken) {
                permissionToken.continuePermissionRequest();
            }
        }).check();
    }

    @SuppressLint("MissingPermission")
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        mMap.setMyLocationEnabled(true);
        mMap.getMapType();
        googleMap.getUiSettings().setZoomControlsEnabled(true);
        googleMap.getUiSettings().setCompassEnabled(true);
        googleMap.getUiSettings().setZoomGesturesEnabled(true);
        googleMap.getUiSettings().setScrollGesturesEnabled(true);
        googleMap.getUiSettings().setRotateGesturesEnabled(false);
        mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);


        LatLng coventry = new LatLng(52.40856, -1.52058);
        mMap.addMarker(new MarkerOptions().position(coventry).title("Coventry"));
        mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(coventry, 11), 5000, null);

        LatLng tesco1 = new LatLng(52.44519, -1.49218);
        mMap.addMarker(new MarkerOptions().position(tesco1).title("Tesco (Arena Park)"));

        LatLng tesco2 = new LatLng(52.43195, -1.51764);
        mMap.addMarker(new MarkerOptions().position(tesco2).title("Tesco (Radford)"));

        LatLng morrisons1 = new LatLng(52.44512, -1.51157);
        mMap.addMarker(new MarkerOptions().position(morrisons1).title("Morrisons (Holbrooks)"));

        LatLng morrisons2 = new LatLng(52.41289, -1.53124);
        mMap.addMarker(new MarkerOptions().position(morrisons2).title("Morrisons (Alvis Retail Park)"));

        LatLng sainsburys1 = new LatLng(52.42683, -1.48216);
        mMap.addMarker(new MarkerOptions().position(sainsburys1).title("Sainsburys (Court House Green)"));

        LatLng sainsburys2 = new LatLng(52.40971, -1.50923);
        mMap.addMarker(new MarkerOptions().position(sainsburys2).title("Sainsburys (Town Centre)"));

        LatLng aldi1 = new LatLng(52.42345, -1.52170);
        mMap.addMarker(new MarkerOptions().position(aldi1).title("Aldi (Radford Rd)"));

        LatLng aldi2 = new LatLng(52.43134, -1.43586);
        mMap.addMarker(new MarkerOptions().position(aldi2).title("Aldi (Walsgrave)"));
    }

    @Override
    public void onSaveInstanceState(@NonNull Bundle outState, @NonNull PersistableBundle outPersistentState) {
        super.onSaveInstanceState(outState, outPersistentState);
        mapView.onSaveInstanceState(outState);
    }

    @Override
    protected void onStart() {
        mapView.onStart();
        super.onStart();
    }

    @Override
    public void onResume() {
        mapView.onResume();
        super.onResume();
    }

    @Override
    protected void onPause() {
        mapView.onPause();
        super.onPause();
    }

    @Override
    public void onDestroy() {
        mapView.onDestroy();
        super.onDestroy();
    }
    @Override
    public void onLowMemory() {
        mapView.onLowMemory();
        super.onLowMemory();
    }

}

XML 文件:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".gMapsActivity"
    android:background="#aaaaaa">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/constraintLayout"
        android:layout_width="432dp"
        android:layout_height="89dp"
        android:layout_marginBottom="1dp"
        android:background="@drawable/gradient"
        app:layout_constraintBottom_toTopOf="@+id/googleMap"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.529"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0">

        <TextView
            android:id="@+id/textView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="98dp"
            android:layout_marginLeft="98dp"
            android:layout_marginTop="30dp"
            android:layout_marginEnd="97dp"
            android:layout_marginRight="97dp"
            android:layout_marginBottom="31dp"
            android:fontFamily="@font/segoeb"
            android:text="@string/supermarket_locator"
            android:textColor="#FFFFFF"
            android:textSize="24sp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
    </androidx.constraintlayout.widget.ConstraintLayout>

    <com.google.android.gms.maps.MapView
        android:id="@+id/googleMap"
        android:layout_width="415dp"
        android:layout_height="643dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="1.0" />

</androidx.constraintlayout.widget.ConstraintLayout>

清单文件:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.recipeverse_app">
    <!--
         The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
         Google Maps Android API v2, but you must specify either coarse or fine
         location permissions for the "MyLocation" functionality.
    -->
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.AppCompat.NoActionBar">
        <activity android:name=".gMapsActivity"/>
        <!--
             The API key for Google Maps-based APIs is defined as a string resource.
             (See the file "res/values/google_maps_api.xml").
             Note that the API key is linked to the encryption key used to sign the APK.
             You need a different API key for each encryption key, including the release key that is used to
             sign the APK for publishing.
             You can define the keys for the debug and release targets in src/debug/ and src/release/.
        -->
        <activity android:name=".SettingsActivity" />
        <activity android:name=".RegisterActivity" />
        <activity android:name=".LoginActivity" />
        <activity android:name=".SignupActivity" />
        <activity android:name=".SplashActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".MainActivity" />
        <activity
            android:name="com.facebook.CustomTabActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />

                <category android:name="android.intent.category.BROWSABLE" />

                <data android:scheme="@string/fb_login_protocol_scheme" />
            </intent-filter>
        </activity>

        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />

        <uses-library
            android:name="org.apache.http.legacy"
            android:required="false" />

        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="AIzaSyBwPwPivWITq7GZdkcLUgLChJS2rHAbBhQ" />

    </application>

</manifest>

LOGCAT:

2021-04-14 21:03:22.189 20835-20835/? I/recipeverse_ap: Not late-enabling -Xcheck:jni (already on)
2021-04-14 21:03:22.196 20835-20835/? I/recipeverse_ap: Unquickening 12 vdex files!
2021-04-14 21:03:22.197 20835-20835/? W/recipeverse_ap: Unexpected CPU variant for X86 using defaults: x86
2021-04-14 21:03:22.227 20835-20835/com.example.recipeverse_app I/recipeverse_ap: The ClassLoaderContext is a special shared library.
2021-04-14 21:03:22.308 20835-20835/com.example.recipeverse_app D/NetworkSecurityConfig: No Network Security Config specified, using platform default
2021-04-14 21:03:22.309 20835-20835/com.example.recipeverse_app D/NetworkSecurityConfig: No Network Security Config specified, using platform default
2021-04-14 21:03:22.320 20835-20835/com.example.recipeverse_app W/ComponentDiscovery: Class com.google.firebase.dynamicloading.DynamicLoadingRegistrar is not an found.
2021-04-14 21:03:22.327 20835-20835/com.example.recipeverse_app I/FirebaseApp: Device unlocked: initializing all Firebase APIs for app [DEFAULT]
2021-04-14 21:03:22.348 20835-20835/com.example.recipeverse_app D/FirebaseAuth: Notifying id token listeners about user ( Y4va5fd39dXlhR1mNwKPfrjBGIh2 ).
2021-04-14 21:03:22.351 20835-20835/com.example.recipeverse_app I/FirebaseInitProvider: FirebaseApp initialization successful
2021-04-14 21:03:22.364 20835-20835/com.example.recipeverse_app I/FacebookInitProvider: Failed to auto initialize the Facebook SDK
    A valid Facebook app id must be set in the AndroidManifest.xml or set by calling FacebookSdk.setApplicationId before initializing the sdk.
        at com.facebook.FacebookSdk.sdkInitialize(FacebookSdk.java:293)
        at com.facebook.FacebookSdk.sdkInitialize(FacebookSdk.java:246)
        at com.facebook.internal.FacebookInitProvider.onCreate(FacebookInitProvider.java:20)
        at android.content.ContentProvider.attachInfo(ContentProvider.java:2388)
        at android.content.ContentProvider.attachInfo(ContentProvider.java:2358)
        at android.app.ActivityThread.installProvider(ActivityThread.java:7239)
        at android.app.ActivityThread.installContentProviders(ActivityThread.java:6780)
        at android.app.ActivityThread.handleBindApplication(ActivityThread.java:6697)
        at android.app.ActivityThread.access00(ActivityThread.java:237)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1913)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:223)
        at android.app.ActivityThread.main(ActivityThread.java:7656)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
2021-04-14 21:03:22.369 20835-20881/com.example.recipeverse_app I/FirebaseAuth: [FirebaseAuth:] Preparing to create service connection to fallback implementation
2021-04-14 21:03:22.380 20835-20885/com.example.recipeverse_app D/libEGL: loaded /vendor/lib/egl/libEGL_emulation.so
2021-04-14 21:03:22.382 20835-20885/com.example.recipeverse_app D/libEGL: loaded /vendor/lib/egl/libGLESv1_CM_emulation.so
2021-04-14 21:03:22.383 20835-20885/com.example.recipeverse_app D/libEGL: loaded /vendor/lib/egl/libGLESv2_emulation.so
2021-04-14 21:03:22.456 20835-20835/com.example.recipeverse_app W/recipeverse_ap: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (greylist, reflection, allowed)
2021-04-14 21:03:22.456 20835-20835/com.example.recipeverse_app W/recipeverse_ap: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (greylist, reflection, allowed)
2021-04-14 21:03:22.506 20835-20835/com.example.recipeverse_app I/zzbz: Making Creator dynamically
2021-04-14 21:03:22.513 20835-20835/com.example.recipeverse_app I/DynamiteModule: Considering local module com.google.android.gms.maps_dynamite:0 and remote module com.google.android.gms.maps_dynamite:201817000
2021-04-14 21:03:22.513 20835-20835/com.example.recipeverse_app I/DynamiteModule: Selected remote version of com.google.android.gms.maps_dynamite, version >= 201817000
2021-04-14 21:03:22.514 20835-20835/com.example.recipeverse_app V/DynamiteModule: Dynamite loader version >= 2, using loadModule2NoCrashUtils
2021-04-14 21:03:22.533 20835-20835/com.example.recipeverse_app W/recipeverse_ap: Unsupported class loader
2021-04-14 21:03:22.544 20835-20835/com.example.recipeverse_app W/recipeverse_ap: Unsupported class loader
2021-04-14 21:03:22.593 20835-20835/com.example.recipeverse_app I/Google Maps Android API: Google Play services client version: 12451000
2021-04-14 21:03:22.601 20835-20835/com.example.recipeverse_app I/Google Maps Android API: Google Play services package version: 201817022
2021-04-14 21:03:22.685 20835-20835/com.example.recipeverse_app D/AndroidRuntime: Shutting down VM
2021-04-14 21:03:22.686 20835-20835/com.example.recipeverse_app E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.recipeverse_app, PID: 20835
    java.lang.NullPointerException: Attempt to invoke interface method 'void com.google.maps.api.android.lib6.impl.bp.v()' on a null object reference
        at com.google.maps.api.android.lib6.impl.cw.h(:com.google.android.gms.dynamite_mapsdynamite@201817052@20.18.17 (040700-0):0)
        at com.google.android.gms.maps.internal.q.a(:com.google.android.gms.dynamite_mapsdynamite@201817052@20.18.17 (040700-0):2)
        at cy.onTransact(:com.google.android.gms.dynamite_mapsdynamite@201817052@20.18.17 (040700-0):4)
        at android.os.Binder.transact(Binder.java:1043)
        at com.google.android.gms.internal.maps.zza.zzb(Unknown Source:20)
        at com.google.android.gms.maps.internal.zzk.onStart(Unknown Source:55)
        at com.google.android.gms.maps.MapView$zza.onStart(Unknown Source:17)
        at com.google.android.gms.dynamic.zag.zaa(com.google.android.gms:play-services-base@@17.1.0:3)
        at com.google.android.gms.dynamic.zaa.onDelegateCreated(com.google.android.gms:play-services-base@@17.1.0:4)
        at com.google.android.gms.maps.MapView$zzb.createDelegate(Unknown Source:16)
        at com.google.android.gms.dynamic.DeferredLifecycleHelper.zaa(com.google.android.gms:play-services-base@@17.1.0:18)
        at com.google.android.gms.dynamic.DeferredLifecycleHelper.onStart(com.google.android.gms:play-services-base@@17.1.0:54)
        at com.google.android.gms.maps.MapView.onStart(Unknown Source:36)
        at com.example.recipeverse_app.gMapsActivity.onStart(gMapsActivity.java:142)
        at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1435)
        at android.app.Activity.performStart(Activity.java:8024)
        at android.app.ActivityThread.handleStartActivity(ActivityThread.java:3475)
        at android.app.servertransaction.TransactionExecutor.performLifecycleSequence(TransactionExecutor.java:221)
        at android.app.servertransaction.TransactionExecutor.cycleToPath(TransactionExecutor.java:201)
        at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:173)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:97)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:223)
        at android.app.ActivityThread.main(ActivityThread.java:7656)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)

感谢帮助。

在 logcat 中你可以看到它在 mapView.onStart 中崩溃了。

这是因为 mapView.onCreatemapView.onStart 之前没有被调用。虽然您在 Activity 的 onCreate 方法中正确地调用了 mapView.onCreate,但它在 if (PermissionGranted) 检查中被关闭,在那个阶段它总是错误的。

您应该可以通过删除 onCreate 中的 'if' 语句来解决此问题,而是 always 从那里调用 mapView.onCreate。然后,您需要将 mapView.getMapAsync(this) 移动到 onPermissionGranted 内以避免未授予权限的 SecurityException。