Android谷歌地图从活动转换为fragement错误

时间:2018-01-10 23:59:23

标签: android android-fragments android-activity google-maps-android-api-2 android-maps

我已经按照教程向我展示了如何在活动中使用google maps api,现在我想将其转换为片段并将其添加到我的选项卡式布局中。 我在片段类中遇到了这个错误。我知道它与我试图获取地图片段的方式有关。

我的片段:

package com.example.andrei.gymhelp;

import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;

import com.example.andrei.gymhelp.GetNearbyPlacesData;
import com.example.andrei.gymhelp.R;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

public class Tab2Maps extends Fragment implements OnMapReadyCallback,
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        LocationListener {

    private GoogleMap mMap;
    double latitude;
    double longitude;
    private int PROXIMITY_RADIUS = 10000;
    GoogleApiClient mGoogleApiClient;
    Location mLastLocation;
    Marker mCurrLocationMarker;
    LocationRequest mLocationRequest;
    private Button btnGym;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.activity_maps, container, false);

        btnGym = rootView.findViewById(R.id.btnGym);
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            checkLocationPermission();
        }

        //Check if Google Play Services Available or not
        if (!CheckGooglePlayServices()) {
            Log.d("onCreate", "Finishing test case since Google Play Services are not available");
            //finish();
        }
        else {
            Log.d("onCreate","Google Play Services available.");
        }

        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getFragmentManager().findFragmentById(R.id.map);


        mapFragment.getMapAsync(this);
        return rootView;
    }

    private boolean CheckGooglePlayServices() {
        GoogleApiAvailability googleAPI = GoogleApiAvailability.getInstance();
        int result = googleAPI.isGooglePlayServicesAvailable(getActivity());
        if(result != ConnectionResult.SUCCESS) {
            if(googleAPI.isUserResolvableError(result)) {
                googleAPI.getErrorDialog(getActivity(), result,
                        0).show();
            }
            return false;
        }
        return true;
    }

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

        //Initialize Google Play Services
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(getActivity(),
                    Manifest.permission.ACCESS_FINE_LOCATION)
                    == PackageManager.PERMISSION_GRANTED) {
                buildGoogleApiClient();
                mMap.setMyLocationEnabled(true);
            }
        }
        else {
            buildGoogleApiClient();
            mMap.setMyLocationEnabled(true);
        }


        btnGym.setOnClickListener(new View.OnClickListener() {
            String Hospital = "gym";
            @Override
            public void onClick(View v) {
                Log.d("onClick", "Button is Clicked");
                mMap.clear();
                String url = getUrl(latitude, longitude, Hospital);
                Object[] DataTransfer = new Object[2];
                DataTransfer[0] = mMap;
                DataTransfer[1] = url;
                Log.d("onClick", url);
                GetNearbyPlacesData getNearbyPlacesData = new GetNearbyPlacesData();
                getNearbyPlacesData.execute(DataTransfer);
                Toast.makeText(getActivity(),"Nearby Gyms", Toast.LENGTH_LONG).show();
            }
        });

    }

    protected synchronized void buildGoogleApiClient() {
        mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
        mGoogleApiClient.connect();
    }

    @Override
    public void onConnected(Bundle bundle) {
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(1000);
        mLocationRequest.setFastestInterval(1000);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
        if (ContextCompat.checkSelfPermission(getActivity(),
                Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
        }
    }

    private String getUrl(double latitude, double longitude, String nearbyPlace) {

        StringBuilder googlePlacesUrl = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
        googlePlacesUrl.append("location=" + latitude + "," + longitude);
        googlePlacesUrl.append("&radius=" + PROXIMITY_RADIUS);
        googlePlacesUrl.append("&type=" + nearbyPlace);
        googlePlacesUrl.append("&sensor=true");
        googlePlacesUrl.append("&key=" + "apikeyhere");
        Log.d("getUrl", googlePlacesUrl.toString());
        return (googlePlacesUrl.toString());
    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onLocationChanged(Location location) {
        Log.d("onLocationChanged", "entered");

        mLastLocation = location;
        if (mCurrLocationMarker != null) {
            mCurrLocationMarker.remove();
        }

        //Place current location marker
        latitude = location.getLatitude();
        longitude = location.getLongitude();
        LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.position(latLng);
        markerOptions.title("Current Position");
        markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
        mCurrLocationMarker = mMap.addMarker(markerOptions);

        //move map camera
        mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
        mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
        Toast.makeText(getActivity(),"Your Current Location", Toast.LENGTH_LONG).show();

        Log.d("onLocationChanged", String.format("latitude:%.3f longitude:%.3f",latitude,longitude));

        //stop location updates
        if (mGoogleApiClient != null) {
            LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
            Log.d("onLocationChanged", "Removing Location Updates");
        }
        Log.d("onLocationChanged", "Exit");

    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {

    }

    public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
    public boolean checkLocationPermission(){
        if (ContextCompat.checkSelfPermission(getActivity(),
                Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {

            // Asking user if explanation is needed
            if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
                    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.

                //Prompt the user once explanation has been shown
                ActivityCompat.requestPermissions(getActivity(),
                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                        MY_PERMISSIONS_REQUEST_LOCATION);


            } else {
                // No explanation needed, we can request the permission.
                ActivityCompat.requestPermissions(getActivity(),
                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                        MY_PERMISSIONS_REQUEST_LOCATION);
            }
            return false;
        } else {
            return true;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], 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. Do the
                    // contacts-related task you need to do.
                    if (ContextCompat.checkSelfPermission(getActivity(),
                            Manifest.permission.ACCESS_FINE_LOCATION)
                            == PackageManager.PERMISSION_GRANTED) {

                        if (mGoogleApiClient == null) {
                            buildGoogleApiClient();
                        }
                        mMap.setMyLocationEnabled(true);
                    }

                } else {

                    // Permission denied, Disable the functionality that depends on this permission.
                    Toast.makeText(getActivity(), "permission denied", Toast.LENGTH_LONG).show();
                }
                return;
            }

            // other 'case' lines to check for other permissions this app might request.
            // You can add here other case statements according to your requirement.
        }
    }
}

错误:

01-11 01:40:00.425 2378-2378/com.example.andrei.gymhelp E/AndroidRuntime: FATAL EXCEPTION: main
                                                                          Process: com.example.andrei.gymhelp, PID: 2378
                                                                          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.andrei.gymhelp.Tab2Maps.onCreateView(Tab2Maps.java:74)
                                                                              at android.support.v4.app.Fragment.performCreateView(Fragment.java:2354)
                                                                              at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1419)
                                                                              at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1740)
                                                                              at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1809)
                                                                              at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:799)
                                                                              at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2580)
                                                                              at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2367)
                                                                              at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2322)
                                                                              at android.support.v4.app.FragmentManagerImpl.execSingleAction(FragmentManager.java:2199)
                                                                              at android.support.v4.app.BackStackRecord.commitNowAllowingStateLoss(BackStackRecord.java:651)
                                                                              at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:145)
                                                                              at android.support.v4.view.ViewPager.populate(ViewPager.java:1236)
                                                                              at android.support.v4.view.ViewPager.populate(ViewPager.java:1084)
                                                                              at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1614)
                                                                              at android.view.View.measure(View.java:22002)
                                                                              at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6580)
                                                                              at android.support.design.widget.CoordinatorLayout.onMeasureChild(CoordinatorLayout.java:714)
                                                                              at android.support.design.widget.HeaderScrollingViewBehavior.onMeasureChild(HeaderScrollingViewBehavior.java:91)
                                                                              at android.support.design.widget.AppBarLayout$ScrollingViewBehavior.onMeasureChild(AppBarLayout.java:1361)
                                                                              at android.support.design.widget.CoordinatorLayout.onMeasure(CoordinatorLayout.java:784)
                                                                              at android.view.View.measure(View.java:22002)
                                                                              at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6580)
                                                                              at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
                                                                              at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:139)
                                                                              at android.view.View.measure(View.java:22002)
                                                                              at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6580)
                                                                              at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1514)
                                                                              at android.widget.LinearLayout.measureVertical(LinearLayout.java:806)
                                                                              at android.widget.LinearLayout.onMeasure(LinearLayout.java:685)
                                                                              at android.view.View.measure(View.java:22002)
                                                                              at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6580)
                                                                              at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
                                                                              at android.view.View.measure(View.java:22002)
                                                                              at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6580)
                                                                              at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1514)
                                                                              at android.widget.LinearLayout.measureVertical(LinearLayout.java:806)
                                                                              at android.widget.LinearLayout.onMeasure(LinearLayout.java:685)
                                                                              at android.view.View.measure(View.java:22002)
                                                                              at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6580)
                                                                              at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
                                                                              at com.android.internal.policy.DecorView.onMeasure(DecorView.java:721)
                                                                              at android.view.View.measure(View.java:22002)
                                                                              at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2410)
                                                                              at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1498)
                                                                              at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1751)
                                                                              at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1386)
                                                                              at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6733)
                                                                              at android.view.Choreographer$CallbackRecord.run(Choreographer.java:911)
                                                                              at android.view.Choreographer.doCallbacks(Choreographer.java:723)
01-11 01:40:00.425 2378-2378/com.example.andrei.gymhelp E/AndroidRuntime:     at android.view.Choreographer.doFrame(Choreographer.java:658)
                                                                              at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:897)
                                                                              at android.os.Handler.handleCallback(Handler.java:789)
                                                                              at android.os.Handler.dispatchMessage(Handler.java:98)
                                                                              at android.os.Looper.loop(Looper.java:164)
                                                                              at android.app.ActivityThread.main(ActivityThread.java:6541)
                                                                              at java.lang.reflect.Method.invoke(Native Method)
                                                                              at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                                                                              at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767

)

0 个答案:

没有答案