无法启动活动...尝试调用虚方法... MapFragment.getMapAsync

时间:2016-06-05 22:27:52

标签: android google-maps android-studio

我的应用程序在nexus 6中打开后会一直崩溃。问题在于getMapAsync()。

public class MainActivity extends AppCompatActivity implements OnMapReadyCallback {

    GoogleMap mMap; //member variable
    private static final int ERROR_DIALOG_REQUEST = 9001; //constant to request certain king of dialog box definition from google play services lib
    private static final double
            AJAX_LAT = 43.851063,
            AJAX_LNG = -79.019737;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (servicesOK()) {
            setContentView(R.layout.activity_main);

            if (initMap()) {
                Toast.makeText(this, "Ready to map!", Toast.LENGTH_SHORT).show();
                gotoLocation(AJAX_LAT, AJAX_LNG, 13);

                //as of now user must grand permissions to app from phone settings
                try {
                    mMap.setMyLocationEnabled(true);
                } catch (SecurityException e) {
                    Toast.makeText(this, "My Location not enabled!", Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(this, "Map not connected!", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(this, "Services not OK!", Toast.LENGTH_SHORT).show();
        }
    }

    //get a reference to the map object
    public boolean initMap() {
        if (mMap == null) {
            MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.map); mapFragment.getMapAsync(this);
        }
        return (mMap != null);
    }
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

    }

    //check to see if the google services are ok
    public boolean servicesOK() {

        GoogleApiAvailability googleAPI = GoogleApiAvailability.getInstance();
        int isAvailable = googleAPI.isGooglePlayServicesAvailable(this);
        // handle 3 different possibility
        if (isAvailable == ConnectionResult.SUCCESS) { //everything ok, user can make mapping request
            return true;
        } else if (googleAPI.isUserResolvableError(isAvailable)) { //error user can do something about
            Dialog dialog = googleAPI.getErrorDialog(this, isAvailable, ERROR_DIALOG_REQUEST);
            dialog.show(); //google play services lib delivers correct dialog box telling user what to do
        } else { //something wrong, user cant do anything about
            Toast.makeText(this, "Can't connect to mapping service", Toast.LENGTH_SHORT).show();
        }
        return false;
    }
}

以下是我得到的错误

Process: com.example.suhail.onmyway, PID: 27425
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.suhail.onmyway/com.example.suhail.onmyway.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.MapFragment.getMapAsync(com.google.android.gms.maps.OnMapReadyCallback)' on a null object reference
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
    at android.app.ActivityThread.-wrap11(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5417)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
 Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.MapFragment.getMapAsync(com.google.android.gms.maps.OnMapReadyCallback)' on a null object reference
    at com.example.suhail.onmyway.MainActivity.initMap(MainActivity.java:89)
    at com.example.suhail.onmyway.MainActivity.onCreate(MainActivity.java:47)
    at android.app.Activity.performCreate(Activity.java:6251)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
    at android.app.ActivityThread.-wrap11(ActivityThread.java) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
    at android.os.Handler.dispatchMessage(Handler.java:102) 
    at android.os.Looper.loop(Looper.java:148) 
    at android.app.ActivityThread.main(ActivityThread.java:5417) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 

我在activity_main.xml中有一个按钮,一旦点击就会打开另一个包含片段的布局     

3 个答案:

答案 0 :(得分:0)

将setContentView放在if块之外 它从第89行坠毁 这条线的代码是什么?

------------更新------------

使用它:

            GoogleMap map = ((WorkaroundMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
            final LatLng GOOGLE_MAP_POSITION = new LatLng(lat, lng);
            Log.d("GOOGLE_MAP", "lat : " + lat + " , lng : " + lng);
            if (map != null) {
                map.clear();
                map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
                Marker marker = map.addMarker(new MarkerOptions().position(GOOGLE_MAP_POSITION)
                        .title("Title")
                        .snippet("Content Goes Here")
                        .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
            }
            MapsInitializer.initialize(this);
            // Move the camera instantly to target with a zoom of 14.
            map.moveCamera(CameraUpdateFactory.newLatLngZoom(GOOGLE_MAP_POSITION, 50));
            // Zoom in, animating the camera, Change 14 to Zoom in And Zoom Out
            map.animateCamera(CameraUpdateFactory.zoomTo(14), 2000, null);

            int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext());
            if (resultCode == ConnectionResult.SUCCESS){
                Log.e("DETAIL_ACTIVITY", "Google Play Services Util Available SUCCESS : "+resultCode);
            }else{
                Log.e("DETAIL_ACTIVITY", "Google Play Services Util Available Problem : "+resultCode);
                GooglePlayServicesUtil.getErrorDialog(resultCode, this, 1);
            }

另外WorkaroundMapFragment是一个自定义类,可让您在ScrollView中使用map

使用它check it out

答案 1 :(得分:0)

可能您的mapFragment为空,也不正确getMapAsync用法,您必须在收到地图后才使用所有属于地图的内容,因此您必须在调用此回调后才采取行动:< / p>

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;

}

在runnable中添加所有下一个初始化并在

之后调用它
mMap = googleMap;

答案 2 :(得分:0)

您必须将此添加到activity_main.xml

<fragment 
    android:name="com.google.android.gms.maps.MapFragment"
    android:id="@+id/map"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>