尝试在'void com.google.android.gms.maps.SupportMapFragment.getMapAsync空对象引用上调用虚拟方法

时间:2018-07-27 04:09:15

标签: android

我正在制作一个应用程序,并且正在使用Googlemaps。 下面是我的代码 我尝试了很多不同的代码,但是没有用

我的应用无法正常工作,并不断出现此错误

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.SupportMapFragment.getMapAsync(com.google.android.gms.maps.OnMapReadyCallback)' on a null object reference
                      at com.example.yoons.honey.Map.onCreate(Map.java:59)

xml代码:

    <?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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=".Map"
tools:layout_editor_absoluteY="81dp">
<Button android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:layout_alignParentStart="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:id="@+id/button"
    android:text="my location"/>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:map="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/map"
    android:name="com.google.android.gms.maps.SupportMapFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.imaadv.leaynik.ClinicFragment"
    android:layout_below="@+id/button"/>

    />

活动代码:

public class Map extends AppCompatActivity  {
private static final String TAG = "MainActivity";

SupportMapFragment mapFragment;
GoogleMap map;

MarkerOptions myLocationMarker;

private CompassView mCompassView;
private SensorManager mSensorManager;
private boolean mCompassEnabled;

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


    mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);

    mapFragment.getMapAsync(new OnMapReadyCallback() { //This is the error I think
        @Override
        public void onMapReady(GoogleMap googleMap) {
            Log.d(TAG, "GoogleMap is ready.");

            map = googleMap;
            onResume();
            map.setMyLocationEnabled(true);
        }
    });





    try {
        MapsInitializer.initialize(this);
    } catch (Exception e) {
        e.printStackTrace();
    }

    Button button = (Button) findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            requestMyLocation();
        }
    });


    mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);


    boolean sideBottom = true;
    mCompassView = new CompassView(this);
    mCompassView.setVisibility(View.VISIBLE);

    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.WRAP_CONTENT,
            RelativeLayout.LayoutParams.WRAP_CONTENT);
    params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
    params.addRule(sideBottom ? RelativeLayout.ALIGN_PARENT_BOTTOM : RelativeLayout.ALIGN_PARENT_TOP);

    ((ViewGroup) mapFragment.getView()).addView(mCompassView, params);


    mCompassEnabled = true;

}




private void requestMyLocation() {
    LocationManager manager =
            (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    try {
        long minTime = 10000;
        float minDistance = 0;
        manager.requestLocationUpdates(
                LocationManager.GPS_PROVIDER,
                minTime,
                minDistance,
                new LocationListener() {
                    @Override
                    public void onLocationChanged(Location location) {
                        showCurrentLocation(location);
                    }

                    @Override
                    public void onStatusChanged(String provider, int status, Bundle extras) {

                    }

                    @Override
                    public void onProviderEnabled(String provider) {

                    }

                    @Override
                    public void onProviderDisabled(String provider) {

                    }
                }
        );

        Location lastLocation = manager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        if (lastLocation != null) {
            showCurrentLocation(lastLocation);
        }

        manager.requestLocationUpdates(
                LocationManager.NETWORK_PROVIDER,
                minTime,
                minDistance,
                new LocationListener() {
                    @Override
                    public void onLocationChanged(Location location) {
                        showCurrentLocation(location);
                    }

                    @Override
                    public void onStatusChanged(String provider, int status, Bundle extras) {

                    }

                    @Override
                    public void onProviderEnabled(String provider) {

                    }

                    @Override
                    public void onProviderDisabled(String provider) {

                    }
                }
        );


    } catch (SecurityException e) {
        e.printStackTrace();
    }
}

private void showCurrentLocation(Location location) {
    LatLng curPoint = new LatLng(location.getLatitude(), location.getLongitude());

    map.animateCamera(CameraUpdateFactory.newLatLngZoom(curPoint, 15));

    showMyLocationMarker(location);
}

private void showMyLocationMarker(Location location) {
    if (myLocationMarker == null) {
        myLocationMarker = new MarkerOptions();
        myLocationMarker.position(new LatLng(location.getLatitude(), location.getLongitude()));
        myLocationMarker.title("�뿈 �궡 �쐞移?n");
        myLocationMarker.snippet("�뿈 GPS濡� �솗�씤�븳 �쐞移�");
        myLocationMarker.icon(BitmapDescriptorFactory.fromResource(R.mipmap.mylocation));
        map.addMarker(myLocationMarker);
    } else {
        myLocationMarker.position(new LatLng(location.getLatitude(), location.getLongitude()));
    }
}


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

    if (map != null) {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, 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.
            return;
        }
        map.setMyLocationEnabled(false);
    }

    if (mCompassEnabled) {
        mSensorManager.unregisterListener(mListener);
    }
}

@Override
protected void onResume() {
    super.onResume();

    if (map != null) {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, 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.
            return;
        }
        map.setMyLocationEnabled(true);
    }

    if(mCompassEnabled) {
        mSensorManager.registerListener(mListener, mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION), SensorManager.SENSOR_DELAY_UI);
    }
}

    private final SensorEventListener mListener = new SensorEventListener() {
    private int iOrientation = Surface.ROTATION_0;

    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }

            public void onSensorChanged(SensorEvent event) {
        if (iOrientation < 0) {
            iOrientation = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getRotation();
        }

        mCompassView.setAzimuth(event.values[0] + 90 * iOrientation);
        mCompassView.invalidate();

    }

};

}

我浏览了很多这样的问题。 我试图夸大我的观点,但是当我尝试

View view = inflater.inflate(R.layout.map, null, false);

充气机上有一条红线。它说它无法解析符号“充气机”

当我尝试使用getChildFragmentManager而不是getSupportFragmentManager时,我也有一条红线

我想我已经获得了所有用户的许可

0 个答案:

没有答案