Kristopher
Kristopher

Reputation: 31

Self permission wrong for Google Map inside fragment activity

I am trying to put a Google Map inside a fragment and this was the error when I tried to initialize its permission checking. Here is my

MapFragment.java

public class MapFragment extends  Fragment implements OnMapReadyCallback {
GoogleMap mGoogleMap;
MapView mMapView;
View mView;
private static final int MY_REQUEST_INT = 177;


private static final String TAG = "MapFragment";

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    mView = inflater.inflate(R.layout.fragment_map, container, false);
    mMapView = (MapView) mView.findViewById(R.id.map);
    if (mMapView != null) {
        mMapView.onCreate(null);
        mMapView.onResume();
        mMapView.getMapAsync(this);
    }
    return mView;

}


@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);


}

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



    /* check location's permission.*/

    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
        //code for permission not granted.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.ACCESS_FINE_LOCATION}, MY_REQUEST_INT);
        }
        return;
    } else {


        //code for permission granted.
        mGoogleMap.setMyLocationEnabled(true);
        mGoogleMap.getUiSettings().setZoomControlsEnabled(true);

    }


   }
}

Error:

Error

Upvotes: 2

Views: 773

Answers (2)

tomerpacific
tomerpacific

Reputation: 6540

You are trying to pass your fragment's context when the method you are calling checkSelfPermission requires the context of your activity.

Try using getActivity().

Upvotes: 3

user3956566
user3956566

Reputation:

this is getting the application. You need to use the current activity - or in the case the activity that has the fragment.

ContextCompat.checkSelfPermission(getActivity(), 
    Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED 
    && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
     != PackageManager.PERMISSION_GRANTED) 

Upvotes: 4

Related Questions