Mudasir Rao Mudasir Rao - 21 days ago 4
Android Question

Not able to fetch the activity context in google maps fragment while setting setMylocationenable(true)

Trying to fecth the current location in the fragment. While getting the permission, not abot to get the activity context. I am getting the activty context in other fragments, but do not know why it shows the error for

mMap.setMyLocationEnabled(true);


Please help

Goole Maps Fragment:

package com.example.mudasir.login.fragments;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.location.Address;
import android.location.Geocoder;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.mudasir.login.R;
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.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

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


/**
* A simple {@link Fragment} subclass.
*/
public class LocatorsFragment extends Fragment implements OnMapReadyCallback, View.OnClickListener {

private GoogleMap mMap;
private Button btnShowroom;
private Button btnService;
private Button btnParts;
private Button btnGas;
private Button btnAtm;
private Button btnSearch;
private EditText searchQuery;


Resources stringArrayResource;
private String[] showroomAddresses;
private String[] serviceAddresses;
private String[] partsAddresses;
private String searchQueryString;
private android.location.Address address = null;
List<Address> addressList = null;

LatLng latLng;
Geocoder geocoder;
Marker marker;
LatLngBounds bounds;
CameraUpdate cu;
ProgressDialog dialog;
boolean flag = false;

public LocatorsFragment() {
}

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_maps_, container, false);
initUI(view);
return view;
}

private void initUI(View view) {
btnShowroom = (Button) view.findViewById(R.id.btn_showroom);
btnService = (Button) view.findViewById(R.id.btn_service);
btnParts = (Button) view.findViewById(R.id.btn_parts);
btnGas = (Button) view.findViewById(R.id.btn_gas);
btnAtm = (Button) view.findViewById(R.id.btn_atm);
btnSearch = (Button) view.findViewById(R.id.btn_search);
searchQuery = (EditText) view.findViewById(R.id.editext_search);

btnShowroom.setOnClickListener(this);
btnService.setOnClickListener(this);
btnParts.setOnClickListener(this);
btnGas.setOnClickListener(this);
btnAtm.setOnClickListener(this);
btnSearch.setOnClickListener(this);

stringArrayResource = getActivity().getResources();
showroomAddresses = stringArrayResource.getStringArray(R.array.showroom_array);
serviceAddresses = stringArrayResource.getStringArray(R.array.service_array);
partsAddresses = stringArrayResource.getStringArray(R.array.parts_array);
}

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.maps);
mapFragment.getMapAsync(this);
}

@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if (ActivityCompat.checkSelfPermission(getActivity(), 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.
}
mMap.setMyLocationEnabled(true);
}

public void render_Map(String[] addresses,LatLngBounds.Builder builder)
{
//mMap.clear();
geocoder = new Geocoder(getActivity());
for (int i = 0; i < 5; i++) {
try {
addressList = geocoder.getFromLocationName(addresses[i], 1);
} catch (IOException e) {
e.printStackTrace();
}
address = addressList.get(0);
latLng = new LatLng(address.getLatitude(), address.getLongitude());
marker = mMap.addMarker(new MarkerOptions().position(latLng).title(addresses[i]));
builder.include(marker.getPosition());
}

bounds = builder.build();
int padding = 0;
cu = CameraUpdateFactory.newLatLngBounds(bounds, padding);
mMap.animateCamera(cu);
}
@Override
public void onClick(View view) {
switch(view.getId()) {
case R.id.btn_showroom:

//new ShowProgressBar().execute("abc",null,null);

LatLngBounds.Builder builder1 = new LatLngBounds.Builder();
render_Map(showroomAddresses,builder1);
flag = true;
// dialog.cancel();
break;

case R.id.btn_service:

LatLngBounds.Builder builder2 = new LatLngBounds.Builder();
render_Map(serviceAddresses,builder2);
break;

case R.id.btn_parts:

LatLngBounds.Builder builder3 = new LatLngBounds.Builder();
render_Map(partsAddresses,builder3);
break;

case R.id.btn_gas:

Toast.makeText(getActivity(),getString(R.string.in_progress_text), Toast.LENGTH_SHORT).show();
break;

case R.id.btn_atm:

Toast.makeText(getActivity(),getString(R.string.in_progress_text), Toast.LENGTH_SHORT).show();
break;

case R.id.btn_search:

searchQueryString = searchQuery.getText().toString();
List<Address> addressList1 = null;

if(searchQueryString != null && !searchQueryString.equals(""))
{
geocoder = new Geocoder(getContext());
try {
addressList1 = geocoder.getFromLocationName(searchQueryString, 1);
} catch (IOException e) {
e.printStackTrace();
}
address = addressList1.get(0);
latLng = new LatLng(address.getLatitude(), address.getLongitude());
mMap.addMarker(new MarkerOptions().position(latLng).title(searchQueryString));
mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
}
else
Toast.makeText(getActivity(),getString(R.string.missing_search_query_error_message), Toast.LENGTH_SHORT).show();
break;

}
}


private class ShowProgressBar extends AsyncTask<String, Void, Void> {

@Override
protected void onPreExecute() {
dialog = ProgressDialog.show(getActivity(), "",
"Loading. Please wait...", true);
}

@Override
protected Void doInBackground(String... strings) {

while (!flag == true)
{
}
return null;
}

@Override

protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
dialog.dismiss();

}
}
}



Error Message: Error:(110, 180) error: incompatible types:
LocatorsFragment cannot be converted to Context

Answer

You are giving this instead of getActivity(). Correct in onMapReady() like this :

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), 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.
    }
    mMap.setMyLocationEnabled(true);
}