Android Runtime Permissions: catching the user's press on "Allow" - android

In my app I've a MapFragment with the classic "MyLocationButton".
On older APIs I don't have any kind of issue, but since Google asked developers to use Runtime Permissions, I'm facing this problem: when the user clicks ALLOW, the already said button is not appearing, at least not until the user refreshes this fragment. Is there a way to catch the user's press to make the fragment refresh as soon as he's given permissions?
EDIT:
I'm using nested fragments, and I've found out my problem is the same you can see at this page of the AOSP Issue Tracker. I've solved it using the last version of Android APIs (v24).
I'll post my MapFragment:
public class MapFragment extends Fragment implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener, PetrolStationsArray.PetrolStationsListener {
private GoogleMap mGoogleMap;
private int mMapType;
private static LatLng mPosition;
private static float mZoom;
private CoordinatorLayout mCoordinatorLayout;
private View mLocationButton;
private AppCompatImageButton mTurnGPSOn;
private FragmentManager mFragmentManager;
private FragmentTransaction mFragmentTransaction;
private SupportMapFragment mSupportMapFragment;
private SupportPlaceAutocompleteFragment mSupportPlaceAutocompleteFragment;
private LocalBroadcastManager mLocalBroadcastManager;
private PetrolStationsArray mPetrolStationsArray;
protected LocationRequest mLocationRequest;
protected GoogleApiClient mGoogleApiClient;
Marker mCurrLocationMarker;
private CountDownTimer mDragTimer;
private boolean mTimerIsRunning = false;
// Design pattern to instantiate a new fragment.
public static MapFragment newInstance() {
MapFragment fragment = new MapFragment();
return fragment;
}
/********************************************************/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Since API 23, Android requests you check for Location Permissions.
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkLocationPermission();
}
mMapType = Integer.parseInt(loadPreferences(SETTINGS_PREFERENCES, MAP_KEY));
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_map, container, false);
mLocalBroadcastManager = LocalBroadcastManager.getInstance(getContext());
mPetrolStationsArray = PetrolStationsArray.get();
mDragTimer = new CountDownTimer(DRAG_TIMER_INTERVAL, DRAG_TIMER_INTERVAL + 1) {
#Override
public void onTick(long l) {
}
#Override
public void onFinish() {
mTimerIsRunning = false;
mPetrolStationsArray.setPosition(mPosition);
}
};
return view;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// Initialise a new fragment inside of this one.
mFragmentManager = getChildFragmentManager();
mSupportMapFragment = (SupportMapFragment) mFragmentManager.findFragmentByTag(MAP_FRAGMENT_TAG);
mSupportPlaceAutocompleteFragment = (SupportPlaceAutocompleteFragment) mFragmentManager.findFragmentByTag(AUTOCOMPLETE_FRAGMENT_TAG);
mCoordinatorLayout = (CoordinatorLayout) view.findViewById(R.id.coordinator_layout);
/*
** Never inflate fragments inside other fragments in a layout.xml!
** Do it programmatically.
** See here for reference: http://stackoverflow.com/a/19815266/4938112.
*/
if (mSupportMapFragment == null) {
mSupportMapFragment = new SupportMapFragment();
fragmentTransaction(mFragmentManager, mSupportMapFragment, R.id.map_fragment_container, MAP_FRAGMENT_TAG);
}
// Asynchronous thread to load map.
mSupportMapFragment.getMapAsync(this);
if (mSupportPlaceAutocompleteFragment == null) {
mSupportPlaceAutocompleteFragment = new SupportPlaceAutocompleteFragment();
fragmentTransaction(mFragmentManager, mSupportPlaceAutocompleteFragment, R.id.card_view, AUTOCOMPLETE_FRAGMENT_TAG);
}
// Filter for a specific place type.
AutocompleteFilter typeFilter = new AutocompleteFilter.Builder()
.setTypeFilter(AutocompleteFilter.TYPE_FILTER_CITIES | AutocompleteFilter.TYPE_FILTER_ADDRESS)
.build();
mSupportPlaceAutocompleteFragment.setFilter(typeFilter);
mSupportPlaceAutocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
LatLng position = place.getLatLng();
CameraUpdate centre = CameraUpdateFactory.newLatLng(position);
CameraUpdate zoom = CameraUpdateFactory.zoomTo(ZOOM_LEVEL);
mGoogleMap.moveCamera(centre);
mGoogleMap.animateCamera(zoom);
}
#Override
public void onError(Status status) {
Log.d("PLACE_ERROR", "An error occurred: " + status);
}
});
mTurnGPSOn = ((AppCompatImageButton) view.findViewById(R.id.turn_gps_on));
mTurnGPSOn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Ask if the user wants to open the GPS - settings.
displayPromptToEnableGPS(getActivity());
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onMapReady(GoogleMap googleMap) {
this.mGoogleMap = googleMap;
mGoogleMap.setMapType(mMapType);
if (mPosition != null) {
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(mPosition, mZoom);
mGoogleMap.moveCamera(cameraUpdate);
}
mGoogleMap.setTrafficEnabled(true);
mGoogleMap.getUiSettings().setMapToolbarEnabled(false);
mGoogleMap.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener() {
#Override
public void onCameraChange(CameraPosition cameraPosition) {
mPosition = cameraPosition.target;
mZoom = cameraPosition.zoom;
if (mTimerIsRunning) {
mDragTimer.cancel();
}
mDragTimer.start();
mTimerIsRunning = true;
}
});
// Get the "My Position" button.
mLocationButton = ((View) mSupportMapFragment.getView().findViewById(Integer.parseInt("1")).getParent()).findViewById(Integer.parseInt("2"));
RelativeLayout.LayoutParams rlp = (RelativeLayout.LayoutParams) mLocationButton.getLayoutParams();
Resources r = getActivity().getResources();
int px = (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
10,
r.getDisplayMetrics()
);
// Position on right bottom.
rlp.addRule(RelativeLayout.ALIGN_PARENT_TOP, 0);
rlp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
rlp.setMargins(0, 0, px, px);
turnOnMyLocation();
}
#Override
public void onPause() {
super.onPause();
// Stop location updates when Activity is no longer active.
if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
mPetrolStationsArray.removePetrolStationListener(this);
}
#Override
public void onResume() {
super.onResume();
mPetrolStationsArray.setPetrolStationsListener(this);
}
#Override
public void onListUpdated() {
// Cleaning all the markers.
if (mGoogleMap != null) {
mGoogleMap.clear();
}
List<PetrolStation> petrolStationList = mPetrolStationsArray.getList();
for (PetrolStation petrolStation : petrolStationList) {
double lat = petrolStation.getLat();
double lon = petrolStation.getLon();
String name = petrolStation.getName();
if (mGoogleMap != null) {
mGoogleMap.addMarker(new MarkerOptions()
.position(new LatLng(lat, lon))
.title(name));
}
}
}
#Override
public void onServerRequest() {
}
#Override
public void onConnected(Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_LOW_POWER);
if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
#Override
public void onConnectionSuspended(int i) {
// TODO
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
// TODO
}
#Override
public void onLocationChanged(Location location) {
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
// Just a check to overtake the
// 'java.lang.IllegalStateException: Fragment MapFragment{42f519d0} not attached to Activity'
// exception I've encountered.
if (!isAdded()) {
return;
}
// Stop location updates.
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
// Start the transaction between different fragments.
private void fragmentTransaction(FragmentManager mFragmentManager, Fragment fragment, int id, String tag) {
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.add(id, fragment, tag);
mFragmentTransaction.commit();
mFragmentManager.executePendingTransactions();
}
/*********************************************
************ LOCATION PERMISSIONS ************
*********************************************/
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, 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) {
turnOnMyLocation();
} else {
// Permission denied, boo! Disable the functionality that depends on this permission.
String message = getResources().getString(R.string.permission_denied);
Snackbar snackbar = Snackbar
.make(mCoordinatorLayout, message, Snackbar.LENGTH_LONG)
.setAction(R.string.close_snack_bar, new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
snackbar.show();
}
}
}
}
// Ask for permission (START DIALOG) in Android APIs >= 23.
public boolean checkLocationPermission() {
if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (shouldShowRequestPermissionRationale(Manifest.permission.ACCESS_FINE_LOCATION)) {
// Prompt the user once explanation has been shown.
requestPermissions(new String[] {
Manifest.permission.ACCESS_FINE_LOCATION
}, MY_PERMISSIONS_REQUEST_LOCATION);
} else {
// No explanation needed, we can request the permission.
requestPermissions(new String[] {
Manifest.permission.ACCESS_FINE_LOCATION
}, MY_PERMISSIONS_REQUEST_LOCATION);
}
return false;
} else {
return true;
}
}
public void turnOnMyLocation() {
// Initialise Google Play Services.
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mGoogleMap.setMyLocationEnabled(true);
}
} else {
mGoogleMap.setMyLocationEnabled(true);
}
}
// Let's build our Location Services API Client.
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient
.Builder(getContext())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
public static void displayPromptToEnableGPS(final Activity activity) {
final AlertDialog.Builder builder = new AlertDialog.Builder(activity);
final String action = Settings.ACTION_LOCATION_SOURCE_SETTINGS;
final String message = MyFuelApp.getAppContext().getResources().getString(R.string.open_gps_settings);
builder.setMessage(message)
.setPositiveButton(MyFuelApp.getAppContext().getResources().getString(R.string.confirm_ok),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface d, int id) {
activity.startActivity(new Intent(action));
d.dismiss();
}
})
.setNegativeButton(MyFuelApp.getAppContext().getResources().getString(R.string.deny_no),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface d, int id) {
d.cancel();
}
});
builder.create().show();
}
}

One way to solve is to ask before open your MapFragment. This way you only have to check if you have the permission or not at your fragment to load one view or another.
The other way, is to add the button at your method turnOnMyLocation().

You can use
onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults)
within this callback you should check the equality of the request code that you passed while requesting permission with the one in the parameter. If it matches, you can get the user result.
If user allow the permission, then you can simply detach and attach your fragment as follow:
Fragment currentFragment = getFragmentManager().findFragmentByTag("FRAGMENT");
FragmentTransaction fragTransaction = getFragmentManager().beginTransaction();
fragTransaction.detach(currentFragment);
fragTransaction.attach(currentFragment);
fragTransaction.commit();
This is how your fragment will be reloaded and also your views gets refreshed. I hope by this you can address your problem.

Related

Android Google Map KMZ/KML Loading Really Slow

I need to loads some KMZ/KML (I tryed both) in my Google Map MapView instance.
But they load really slow, they are 8 KMZ of around 300KB each and for each one it takes more than 3/4 seconds to get loaded.
How can I solve this?
Surfing in search of a solution I found they suggest to use the V3 version because it fix a polyline creation cycle really time consuming in V2.
This is the library:
implementation 'com.google.maps.android:android-maps-utils-v3:1.3.1'
The problem is that when I use this library the constructors of KmlLayer stop working because inside the class KmlLayer it doesn't found the following package of the GoogleMap class, so because all the constructors require a GoogleMap instance they stop working:
import com.google.android.libraries.maps.GoogleMap;
How can I solve this? Is using the V3 version a solution to my problem? If no how can I solve this?
I found other people having the same problem but when they load KML of 10MB or more and not of just 300KB...
This is the class where there is the MapView instance:
public class MappaNuovoGuastoFragment extends Fragment
implements OnMapReadyCallback,
GetLocationManager.OnLocationUpdateCallback,
GoogleMap.OnMapClickListener,
GoogleMap.OnMapLongClickListener,
BaseRetrofitHelper.INetworkResponseCallback {
private static final String TAG = MappaNuovoGuastoFragment.class.getSimpleName();
// Requests Codes - Permission
private static final int REQ_PERMISSION_LOCATION = 0xB01;
// Requests Codes - Networking
private static final int REQ_CODE_PLACES_AUTOCOMPLETE = 0x1;
private static final int REQ_CODE_GET_PLACE_DETAIL = 0x2;
#BindView(R.id.ll_search)
protected LinearLayout mllSearch;
#BindView(R.id.actv_search_field)
protected AutoCompleteTextView mactvSearchField;
#BindView(R.id.map_view)
protected MapView mMapView;
private GoogleMap mGoogleMap;
private GetLocationManager mGetLocationManager;
private LatLng mMyLocation;
private LatLng mClickedLocation;
private Marker mMarker;
private List<GoogleMapPlace> mPlaces;
public static MappaNuovoGuastoFragment newInstance(){
return new MappaNuovoGuastoFragment();
}
//region [#] Override Lifecycle Methods
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_mappa_nuovo_guasto, container, false);
ButterKnife.bind(this, view);
initOnCreateView(savedInstanceState);
return view;
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQ_PERMISSION_LOCATION) {
if (grantResults.length > 0x0) {
for (int res : grantResults) {
if (res == PackageManager.PERMISSION_GRANTED) {
mMapView.getMapAsync(this);
break;
}
}
}
}
}
#Override
public void onResume() {
super.onResume();
mMapView.onResume();
mGetLocationManager.startLocationUpdates();
}
#Override
public void onPause() {
mGetLocationManager.stopLocationUpdates();
mMapView.onPause();
super.onPause();
}
#Override
public void onDestroy() {
if(mMapView != null){
mMapView.onDestroy();
}
super.onDestroy();
}
#Override
public void onLowMemory() {
mMapView.onLowMemory();
super.onLowMemory();
}
//endregion
//region [#] Actions Methods
#OnClick(R.id.ib_search)
void onClickSearch(View view){
GoogleMapPlace place = null;
if(mPlaces != null && !mPlaces.isEmpty()){
for(GoogleMapPlace p : mPlaces){
if(p.getDescription().equals(mactvSearchField.getText().toString())){
place = p;
break;
}
}
}
if(place != null){
requestPlaceDetails(place.getPlaceId());
} else {
showSnackbarLocationNotFound();
}
}
#OnClick(R.id.b_make)
void onClickMake(View view){
if(mClickedLocation != null || mMyLocation != null){
startActivityGeneraGuasto();
}
}
#OnClick(R.id.b_map_type)
void onClickMapType(View view){
if(mGoogleMap != null){
switch (mGoogleMap.getMapType()){
case GoogleMap.MAP_TYPE_NONE:
case GoogleMap.MAP_TYPE_HYBRID:
case GoogleMap.MAP_TYPE_SATELLITE:
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
break;
case GoogleMap.MAP_TYPE_NORMAL:
case GoogleMap.MAP_TYPE_TERRAIN:
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
break;
}
}
}
//endregion
//region [#] Override OnMapReadyCallback Methods
#Override
public void onMapReady(#NonNull GoogleMap googleMap) {
mGoogleMap = googleMap;
initGoogleMap();
loadKmz();
}
//endregion
//region [#] Override GetLocationManager.OnLocationUpdateCallback Methods
#Override
public void onLocationUpdated(#Nullable Location location) {
if(mMyLocation == null){
mMyLocation = location != null ? new LatLng(location.getLatitude(), location.getLongitude()) : null;
if(mMyLocation != null){
mGoogleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(mMyLocation, 16.0f));
}
} else {
mMyLocation = location != null ? new LatLng(location.getLatitude(), location.getLongitude()) : null;
}
}
//endregion
//region [#] Override GoogleMap.OnMapClickListener Methods
#Override
public void onMapClick(#NonNull LatLng latLng) {
mClickedLocation = latLng;
initMark();
}
//endregion
//region [#] Override GoogleMap.OnMapLongClickListener Methods
#Override
public void onMapLongClick(#NonNull LatLng latLng) {
if(mClickedLocation != null && PositionUtils.distanceBetween(mClickedLocation.latitude, mClickedLocation.longitude, latLng.latitude, latLng.longitude) <= 100){
mClickedLocation = null;
mMarker.remove();
mMarker = null;
}
}
//endregion
//region [#] Override BaseRetrofitHelper.INetworkResponseCallback Methods
#Override
public void onNetworkResponseSuccess(int requestCode, Object answer) {
switch (requestCode){
case REQ_CODE_PLACES_AUTOCOMPLETE:
if(answer != null){
mPlaces = ((GoogleApiPlaceAutocompleteResponse)answer).getPlaces();
List<String> strings = new ArrayList<>();
for(GoogleMapPlace place : mPlaces){
strings.add(place.getDescription());
}
((ArrayAdapter<String>)mactvSearchField.getAdapter()).clear();
((ArrayAdapter<String>)mactvSearchField.getAdapter()).addAll(strings);
}
break;
case REQ_CODE_GET_PLACE_DETAIL:
if(answer != null){
LatLng latlng = ((GoogleApiPlaceDetailsResponse)answer).getResult().getLatLng();
onMapClick(latlng);
mGoogleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latlng, 15));
} else {
showSnackbarLocationNotFound();
}
break;
}
}
#Override
public void onNetworkResponseError(int requestCode, Throwable t) {
switch (requestCode){
case REQ_CODE_GET_PLACE_DETAIL:
showSnackbarLocationNotFound();
break;
}
}
//endregion
//region [#] Private Methods
private void initOnCreateView(Bundle savedInstanceState){
mMapView.onCreate(savedInstanceState);
mMapView.onResume();
try {
MapsInitializer.initialize(requireActivity().getApplicationContext());
} catch (Exception e){
EMaxLogger.onException(TAG, e);
e.printStackTrace();
}
mMapView.getMapAsync(this);
mGetLocationManager = GetLocationManager.initInstance(requireActivity()).setCallback(this);
initAutocompleteTextView();
mllSearch.bringToFront();
}
private void initGoogleMap(){
if (ActivityCompat.checkSelfPermission(requireContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(requireContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(requireActivity(), new String[]{ Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION }, REQ_PERMISSION_LOCATION);
} else {
mGoogleMap.setMyLocationEnabled(true);
}
mGoogleMap.setOnMapClickListener(this);
mGoogleMap.setOnMapLongClickListener(this);
}
private void initMark(){
if(mMarker != null){
mMarker.remove();
}
LatLng pos = new LatLng(mClickedLocation.latitude, mClickedLocation.longitude);
MarkerOptions opt = new MarkerOptions().position(pos).title(getString(R.string.label_nuovo_guasto));
opt.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_mark_work));
mMarker = mGoogleMap.addMarker(opt);
mGoogleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(pos, 16.0f));
if (mMarker != null) {
mMarker.showInfoWindow();
}
}
private void initAutocompleteTextView(){
ArrayAdapter<String> adapter = new ArrayAdapter<String>(requireContext(), android.R.layout.select_dialog_item, new ArrayList<>());
mactvSearchField.setThreshold(0x4);
mactvSearchField.setAdapter(adapter);
mactvSearchField.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
if(s.toString().length() >= 0x4){
requestPlaceAutocomplete(s.toString());
}
}
});
}
private void startActivityGeneraGuasto(){
startActivity(GeneraGuastoActivity.getIntent(requireContext(), mClickedLocation != null ? mClickedLocation.latitude : mMyLocation.latitude, mClickedLocation != null ? mClickedLocation.longitude : mMyLocation.longitude));
}
private void showSnackbarLocationNotFound(){
DesignUtils.showSnackbar(mactvSearchField, getString(R.string.error_location_not_found), Snackbar.LENGTH_SHORT);
}
//region [#] Requests Methods
private void requestPlaceAutocomplete(String input){
String key = getString(R.string.google_maps_key);
String components = String.format("country:%1$s", ((TelephonyManager)getActivity().getSystemService(Context.TELEPHONY_SERVICE)).getNetworkCountryIso());
TicketRetrofitHelper.getInstance().requestAsyncGetPlaceAutocomplete(TicketConstants.URL_GOOGLE_API_PLACE_AUTOCOMPLETE, key, input, components, REQ_CODE_PLACES_AUTOCOMPLETE, this);
}
private void requestPlaceDetails(String idPlace){
String key = getString(R.string.google_maps_key);
TicketRetrofitHelper.getInstance().requestAsyncGetPlaceDetails(TicketConstants.URL_GOOGLE_API_PLACE_DETAILS, key, idPlace, REQ_CODE_GET_PLACE_DETAIL, this);
}
//endregion
private void loadKmz(){
try {
KmlLayer kmz1 = new KmlLayer(mGoogleMap, R.raw.centri_abitati_1, requireContext());
KmlLayer kmz2 = new KmlLayer(mGoogleMap, R.raw.centri_abitati_2, requireContext());
KmlLayer kmz3 = new KmlLayer(mGoogleMap, R.raw.confini_comuni_1, requireContext());
KmlLayer kmz4 = new KmlLayer(mGoogleMap, R.raw.confini_comuni_2, requireContext());
KmlLayer kmz5 = new KmlLayer(mGoogleMap, R.raw.viabilita_1, requireContext());
KmlLayer kmz6 = new KmlLayer(mGoogleMap, R.raw.viabilita_2, requireContext());
KmlLayer kmz7 = new KmlLayer(mGoogleMap, R.raw.viabilita_3, requireContext());
KmlLayer kmz8 = new KmlLayer(mGoogleMap, R.raw.viabilita_4, requireContext());
kmz1.addLayerToMap();
kmz2.addLayerToMap();
kmz3.addLayerToMap();
kmz4.addLayerToMap();
kmz5.addLayerToMap();
kmz6.addLayerToMap();
kmz7.addLayerToMap();
kmz8.addLayerToMap();
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
//endregion
}

Getting current device location on Fragment

I want to get current (or last known) device location and move the camera to it on map when the app starts. I have tried so many ways, but nothing works on Fragment.
Here is my current code with whom the app turns off immediately.
MapFragment.java
public class MapFragment extends Fragment implements OnMapReadyCallback
{
private GoogleMap mGoogleMap;
private FusedLocationProviderClient mFusedLocationProviderClient;
private static final int PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 1;
private boolean mLocationPermissionGranted;
private Location mLastKnownLocation;
private final LatLng mDefaultLocation = new LatLng(-33.8523341, 151.2106085);
private static final int DEFAULT_ZOOM = 15;
public MapFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this.getActivity());
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View mView = inflater.inflate(R.layout.fragment_map, container, false);
return mView;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
MapsInitializer.initialize(getContext());
mGoogleMap = googleMap;
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
// Turn on the My Location layer and the related control on the map.
updateLocationUI();
// Get the current location of the device and set the position of the map.
getDeviceLocation();
}
private void getLocationPermission() {
/*
* Request location permission, so that we can get the location of the
* device. The result of the permission request is handled by a callback,
* onRequestPermissionsResult.
*/
if (ContextCompat.checkSelfPermission(this.getActivity(),
android.Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
mLocationPermissionGranted = true;
} else {
ActivityCompat.requestPermissions(this.getActivity(),
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String permissions[], #NonNull int[] grantResults) {
mLocationPermissionGranted = false;
switch (requestCode) {
case PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
mLocationPermissionGranted = true;
}
}
}
updateLocationUI();
}
private void updateLocationUI() {
if (mGoogleMap == null) {
return;
}
try {
if (mLocationPermissionGranted) {
mGoogleMap.setMyLocationEnabled(true);
mGoogleMap.getUiSettings().setMyLocationButtonEnabled(true);
} else {
mGoogleMap.setMyLocationEnabled(false);
mGoogleMap.getUiSettings().setMyLocationButtonEnabled(false);
mLastKnownLocation = null;
getLocationPermission();
}
} catch (SecurityException e) {
Log.e("Exception: %s", e.getMessage());
}
}
private void getDeviceLocation() {
/*
* Get the best and most recent location of the device, which may be null in rare
* cases when a location is not available.
*/
try {
if (mLocationPermissionGranted) {
Task locationResult = mFusedLocationProviderClient.getLastLocation();
locationResult.addOnCompleteListener((Executor) this, new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if (task.isSuccessful()) {
// Set the map's camera position to the current location of the device.
mLastKnownLocation = (Location) task.getResult();
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(mLastKnownLocation.getLatitude(),
mLastKnownLocation.getLongitude()), DEFAULT_ZOOM));
} else {
Log.d(TAG, "Current location is null. Using defaults.");
Log.e(TAG, "Exception: %s", task.getException());
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(mDefaultLocation, DEFAULT_ZOOM));
mGoogleMap.getUiSettings().setMyLocationButtonEnabled(false);
}
}
});
}
} catch(SecurityException e) {
Log.e("Exception: %s", e.getMessage());
}
}
This way works on FragmentActivity, but not on Fragment.
I've also given ACCESS_FINE_LOCATION permission in AndroindManifest.xml.

My map shows but my markers dosnt in google maps [duplicate]

I managed to implement a TabLayout. Within one of the tabs is a Google Maps Fragment. I want to ask permission to access the user's location and then place a marker on the current location. As of right now, the dialog box does not show up and I do not know why. Can anyone help me?
public class MapsFragment extends Fragment implements OnMapReadyCallback{
GoogleMap mGoogleMap;
MapView mMapView;
View mView;
LocationManager locationManager;
static final int REQUEST_LOCATION = 1;
public MapsFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
mView = inflater.inflate(R.layout.fragment_maps,container,false);
return mView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState){
super.onViewCreated(view, savedInstanceState);
mMapView = (MapView) mView.findViewById(R.id.googleMap);
if(mMapView != null){
mMapView.onCreate(null);
mMapView.onResume();
mMapView.getMapAsync(this);
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
//Initialize Google PLay Services
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
if(ContextCompat.checkSelfPermission(getContext(),
Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
//Location Permission is gratned
MapsInitializer.initialize(getContext());
mGoogleMap.setMyLocationEnabled(true);
}
}
googleMap.addMarker(new MarkerOptions().position(new LatLng(36.652527, -121.797277)).title("CSUMB"));
CameraPosition CSUMB = CameraPosition.builder().target(new LatLng(36.6538, -121.797277)).zoom(16).bearing(0).tilt(45).build();
googleMap.moveCamera(CameraUpdateFactory.newCameraPosition(CSUMB));
}
void getLocation(){
locationManager = (LocationManager)getActivity()
.getSystemService(Context.LOCATION_SERVICE);
getLocation();
if(ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(),
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED){
}else{
Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if(location!= null){
double latti = location.getLatitude();
double longi = location.getLongitude();
Toast.makeText(getActivity(),"Location is " + String.valueOf(latti) + ", " + String.valueOf(longi),Toast.LENGTH_LONG);
Log.e("Maps Fragment", "Location is: " + String.valueOf(latti) + ", " + String.valueOf(longi));
}
else{
Log.e("Maps fragment", "Unable to find current location.");
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST_LOCATION:
getLocation();
break;
}
}
#Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mMapView.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
mMapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mMapView.onLowMemory();
}
}
This is very close to my other answer here, however, that answer doesn't explain how to do it using a ViewPager with a TabLayout.
First, the piece that sets this apart from the other answer, you'll need to keep a reference to the current Fragment in the FragmentPagerAdapter using the instantiateItem() override.
Also, note that the onRequestPermissionsResult() method is needed here in the Activity in order to route the user's permission request response to the Fragment.
Here is the full Activity code:
public class MainActivity extends AppCompatActivity {
ViewPager viewPager;
PagerAdapter pagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Get the ViewPager and set it's PagerAdapter so that it can display items
viewPager = (ViewPager) findViewById(R.id.viewpager);
pagerAdapter = new PagerAdapter(getSupportFragmentManager(), MainActivity.this);
viewPager.setAdapter(pagerAdapter);
// Give the TabLayout the ViewPager
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.setupWithViewPager(viewPager);
// Iterate over all tabs and set the custom view
for (int i = 0; i < tabLayout.getTabCount(); i++) {
TabLayout.Tab tab = tabLayout.getTabAt(i);
tab.setCustomView(pagerAdapter.getTabView(i));
}
}
class PagerAdapter extends FragmentPagerAdapter {
String tabTitles[] = new String[] { "Tab One", "Tab Two", "Tab Three", };
public Fragment[] fragments = new Fragment[tabTitles.length];
Context context;
public PagerAdapter(FragmentManager fm, Context context) {
super(fm);
this.context = context;
}
#Override
public int getCount() {
return tabTitles.length;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new MapFragment();
case 1:
return new BlankFragment();
case 2:
return new BlankFragment();
}
return null;
}
#Override
public CharSequence getPageTitle(int position) {
// Generate title based on item position
return tabTitles[position];
}
public View getTabView(int position) {
View tab = LayoutInflater.from(MainActivity.this).inflate(R.layout.custom_tab, null);
TextView tv = (TextView) tab.findViewById(R.id.custom_text);
tv.setText(tabTitles[position]);
return tab;
}
//This populates your Fragment reference array:
#Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment createdFragment = (Fragment) super.instantiateItem(container, position);
fragments[position] = createdFragment;
return createdFragment;
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
if (requestCode == MapFragment.MY_PERMISSIONS_REQUEST_LOCATION){
MapFragment mapFragment = (MapFragment) pagerAdapter.fragments[0];
if (mapFragment != null) {
mapFragment.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
else {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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"
android:fitsSystemWindows="true"
tools:context=".MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay"
android:elevation="6dp">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
android:elevation="0dp" />
<android.support.design.widget.TabLayout
android:id="#+id/tab_layout"
app:tabMode="fixed"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/toolbar"
android:background="?attr/colorPrimary"
android:elevation="0dp"
app:tabTextColor="#d3d3d3"
app:tabSelectedTextColor="#ffffff"
app:tabIndicatorColor="#ff00ff"
android:minHeight="?attr/actionBarSize"
/>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="fill_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
/>
</android.support.design.widget.CoordinatorLayout>
custom_tab.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/custom_text"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:background="?attr/selectableItemBackground"
android:gravity="center"
android:textSize="16dip"
android:textColor="#ffffff"
android:maxLines="1"
/>
</LinearLayout>
For the Map Fragment, use essentially the same code as the other answer:
public class MapFragment extends SupportMapFragment
implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
GoogleMap mGoogleMap;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
#Override
public void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
if (mGoogleMap == null) {
getMapAsync(this);
}
}
#Override
public void onPause() {
super.onPause();
//stop location updates when Activity is no longer active
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
#Override
public void onMapReady(GoogleMap googleMap)
{
mGoogleMap=googleMap;
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
//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) {
//Location Permission already granted
buildGoogleApiClient();
mGoogleMap.setMyLocationEnabled(true);
} else {
//Request Location Permission
checkLocationPermission();
}
}
else {
buildGoogleApiClient();
mGoogleMap.setMyLocationEnabled(true);
}
}
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);
}
}
#Override
public void onConnectionSuspended(int i) {}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {}
#Override
public void onLocationChanged(Location location)
{
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
//Place current location marker
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 = mGoogleMap.addMarker(markerOptions);
//move map camera
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(11));
//optionally, stop location updates if only current location is needed
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
private void checkLocationPermission() {
if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
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.
new AlertDialog.Builder(getActivity())
.setTitle("Location Permission Needed")
.setMessage("This app needs the Location permission, please accept to use location functionality")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(getActivity(),
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION );
}
})
.create()
.show();
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(getActivity(),
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION );
}
}
}
#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, yay! Do the
// location-related task you need to do.
if (ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
mGoogleMap.setMyLocationEnabled(true);
}
} else {
// permission denied, boo! 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
}
}
}
Result
First, the location permission prompt:
Once the user has accepted the permission at runtime, show the user's current location:

Have tabs preload their Fragments when app starts and have tabs save state

I have 3 tabs:
Home
Google Map
Settings
I have a main activity which has a TabLayout to show the 3 tabs:
public class MainActivity extends AppCompatActivity implements MyMapFragment.OnFragmentInteractionListener, SettingsFragment.OnFragmentInteractionListener {
private static final int INDEX_HOME_FRAGMENT = 0;
private static final int INDEX_MAP_FRAGMENT = 1;
private static final int INDEX_SETTINGS_FRAGMENT = 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("Home"));
tabLayout.addTab(tabLayout.newTab().setText("Map"));
tabLayout.addTab(tabLayout.newTab().setText("Settings"));
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
switch(tab.getPosition()) {
case INDEX_HOME_FRAGMENT:
HomeFragment homeFragment = new HomeFragment();
transaction.replace(R.id.frame_layout, homeFragment);
// Commit the transaction
transaction.commit();
break;
case INDEX_MAP_FRAGMENT:
MyMapFragment myMapFragment = new MyMapFragment();
transaction.replace(R.id.frame_layout, myMapFragment);
// Commit the transaction
transaction.commit();
break;
case INDEX_SETTINGS_FRAGMENT:
SettingsFragment settingsFragment = new SettingsFragment();
transaction.replace(R.id.frame_layout, settingsFragment);
// Commit the transaction
transaction.commit();
break;
default:
//error occured here
Log.e("Error occured = ", " TAB_ERROR");
break;
}
}
});
// Check that the activity is using the layout version with
// the fragment_container FrameLayout
if (findViewById(R.id.frame_layout) != null) {
if (savedInstanceState != null) {
return;
}
HomeFragment homeFragment = new HomeFragment();
// Add the fragment to the 'fragment_container' FrameLayout
getSupportFragmentManager().beginTransaction()
.add(R.id.frame_layout, homeFragment ).commit();
}
}
#Override
public void onFragmentInteraction(Uri uri) {
//do nothing
}
}
This Activity also handles when a tab gets clicked. When a tab gets clicked it should show the Fragment in the FrameLayout.
This all works fine. The only problem is when I click the Maps tab, Google maps always refreshes.
I want the map to preload when the app starts so when the user clicks the map tab the map shoudl already be loaded. As well when the user goes away from the map tab and comes back it should save the map as it was previously. Currently when the user goes back to the map tab the map is reloaded and it takes again some time for it to load.
This is my map Fragment:
public class MyMapFragment extends SupportMapFragment
implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
GoogleMap mGoogleMap;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
Marker lastOpenned = null;
#Override
public void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
if (mGoogleMap == null) {
getMapAsync(this);
}
}
#Override
public void onPause() {
super.onPause();
//stop location updates when Activity is no longer active
if (mGoogleApiClient != null) {
//LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient,this);
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
LatLngBounds.Builder builder = new LatLngBounds.Builder();
mGoogleMap.addMarker(new MarkerOptions()
.position(new LatLng(40.76793169992044, -73.98180484771729))
.title("San Francisco"));
mGoogleMap.addMarker(new MarkerOptions()
.position(new LatLng(41.76793169992044, -72.98180484771729))
.title("Las Vegas"));
builder.include(new LatLng(40.76793169992044, -73.98180484771729));
builder.include(new LatLng(41.76793169992044, -72.98180484771729));
LatLngBounds bounds = builder.build();
mGoogleMap.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds, 200));
mGoogleMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
public boolean onMarkerClick(Marker marker) {
return true;
}
});
//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) {
//Location Permission already granted
buildGoogleApiClient();
mGoogleMap.setMyLocationEnabled(true);
} else {
//Request Location Permission
checkLocationPermission();
}
} else {
buildGoogleApiClient();
mGoogleMap.setMyLocationEnabled(true);
}
}
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);
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onLocationChanged(Location location) {
}
private void checkLocationPermission() {
if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
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.
new AlertDialog.Builder(getActivity())
.setTitle("Location Permission Needed")
.setMessage("This app needs the Location permission, please accept to use location functionality")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(getActivity(),
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
})
.create()
.show();
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(getActivity(),
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
}
}
#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, yay! Do the
// location-related task you need to do.
if (ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
mGoogleMap.setMyLocationEnabled(true);
}
} else {
// permission denied, boo! 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
}
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
I would suggest not making new MyMapFragment() every time you click the tab if you don't want the map to reload.
A simple way to do that is a simple wrapper Fragment holder class.
public class MainActivity extends AppCompatActivity
implements MyMapFragment.OnFragmentInteractionListener, SettingsFragment.OnFragmentInteractionListener {
static class FragmentTab {
String name;
Fragment frag;
public FragmentTab(String name, Fragment f) {
this.name = name;
this.frag = f;
}
}
// These are only created once, not per-click
private List<FragmentTab> tabs = Arrays.asList(
new FragmentTab("Home", new HomeFragment()),
new FragmentTab("Map", new MyMapFragment()),
new FragmentTab("Settings", new SettingsFragment()),
);
Then, you can iterate and index that list to clean up the rest of your code
for (FragmentTab tab : tabs) {
tabLayout.addTab(tabLayout.newTab().setText(tab.name));
}
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.frame_layout, tabs.get(tab.getPosition()).frag)
.commit();
}
};
A LinkedHashMap<String, Fragment> would also work, but replacing tab.getPosition() for tab.getTitle() (I think)

Google maps fragment into a viewpager activity [duplicate]

I managed to implement a TabLayout. Within one of the tabs is a Google Maps Fragment. I want to ask permission to access the user's location and then place a marker on the current location. As of right now, the dialog box does not show up and I do not know why. Can anyone help me?
public class MapsFragment extends Fragment implements OnMapReadyCallback{
GoogleMap mGoogleMap;
MapView mMapView;
View mView;
LocationManager locationManager;
static final int REQUEST_LOCATION = 1;
public MapsFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
mView = inflater.inflate(R.layout.fragment_maps,container,false);
return mView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState){
super.onViewCreated(view, savedInstanceState);
mMapView = (MapView) mView.findViewById(R.id.googleMap);
if(mMapView != null){
mMapView.onCreate(null);
mMapView.onResume();
mMapView.getMapAsync(this);
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
//Initialize Google PLay Services
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
if(ContextCompat.checkSelfPermission(getContext(),
Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
//Location Permission is gratned
MapsInitializer.initialize(getContext());
mGoogleMap.setMyLocationEnabled(true);
}
}
googleMap.addMarker(new MarkerOptions().position(new LatLng(36.652527, -121.797277)).title("CSUMB"));
CameraPosition CSUMB = CameraPosition.builder().target(new LatLng(36.6538, -121.797277)).zoom(16).bearing(0).tilt(45).build();
googleMap.moveCamera(CameraUpdateFactory.newCameraPosition(CSUMB));
}
void getLocation(){
locationManager = (LocationManager)getActivity()
.getSystemService(Context.LOCATION_SERVICE);
getLocation();
if(ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(),
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED){
}else{
Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if(location!= null){
double latti = location.getLatitude();
double longi = location.getLongitude();
Toast.makeText(getActivity(),"Location is " + String.valueOf(latti) + ", " + String.valueOf(longi),Toast.LENGTH_LONG);
Log.e("Maps Fragment", "Location is: " + String.valueOf(latti) + ", " + String.valueOf(longi));
}
else{
Log.e("Maps fragment", "Unable to find current location.");
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST_LOCATION:
getLocation();
break;
}
}
#Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mMapView.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
mMapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mMapView.onLowMemory();
}
}
This is very close to my other answer here, however, that answer doesn't explain how to do it using a ViewPager with a TabLayout.
First, the piece that sets this apart from the other answer, you'll need to keep a reference to the current Fragment in the FragmentPagerAdapter using the instantiateItem() override.
Also, note that the onRequestPermissionsResult() method is needed here in the Activity in order to route the user's permission request response to the Fragment.
Here is the full Activity code:
public class MainActivity extends AppCompatActivity {
ViewPager viewPager;
PagerAdapter pagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Get the ViewPager and set it's PagerAdapter so that it can display items
viewPager = (ViewPager) findViewById(R.id.viewpager);
pagerAdapter = new PagerAdapter(getSupportFragmentManager(), MainActivity.this);
viewPager.setAdapter(pagerAdapter);
// Give the TabLayout the ViewPager
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.setupWithViewPager(viewPager);
// Iterate over all tabs and set the custom view
for (int i = 0; i < tabLayout.getTabCount(); i++) {
TabLayout.Tab tab = tabLayout.getTabAt(i);
tab.setCustomView(pagerAdapter.getTabView(i));
}
}
class PagerAdapter extends FragmentPagerAdapter {
String tabTitles[] = new String[] { "Tab One", "Tab Two", "Tab Three", };
public Fragment[] fragments = new Fragment[tabTitles.length];
Context context;
public PagerAdapter(FragmentManager fm, Context context) {
super(fm);
this.context = context;
}
#Override
public int getCount() {
return tabTitles.length;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new MapFragment();
case 1:
return new BlankFragment();
case 2:
return new BlankFragment();
}
return null;
}
#Override
public CharSequence getPageTitle(int position) {
// Generate title based on item position
return tabTitles[position];
}
public View getTabView(int position) {
View tab = LayoutInflater.from(MainActivity.this).inflate(R.layout.custom_tab, null);
TextView tv = (TextView) tab.findViewById(R.id.custom_text);
tv.setText(tabTitles[position]);
return tab;
}
//This populates your Fragment reference array:
#Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment createdFragment = (Fragment) super.instantiateItem(container, position);
fragments[position] = createdFragment;
return createdFragment;
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
if (requestCode == MapFragment.MY_PERMISSIONS_REQUEST_LOCATION){
MapFragment mapFragment = (MapFragment) pagerAdapter.fragments[0];
if (mapFragment != null) {
mapFragment.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
else {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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"
android:fitsSystemWindows="true"
tools:context=".MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay"
android:elevation="6dp">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
android:elevation="0dp" />
<android.support.design.widget.TabLayout
android:id="#+id/tab_layout"
app:tabMode="fixed"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/toolbar"
android:background="?attr/colorPrimary"
android:elevation="0dp"
app:tabTextColor="#d3d3d3"
app:tabSelectedTextColor="#ffffff"
app:tabIndicatorColor="#ff00ff"
android:minHeight="?attr/actionBarSize"
/>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="fill_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
/>
</android.support.design.widget.CoordinatorLayout>
custom_tab.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/custom_text"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:background="?attr/selectableItemBackground"
android:gravity="center"
android:textSize="16dip"
android:textColor="#ffffff"
android:maxLines="1"
/>
</LinearLayout>
For the Map Fragment, use essentially the same code as the other answer:
public class MapFragment extends SupportMapFragment
implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
GoogleMap mGoogleMap;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
#Override
public void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
if (mGoogleMap == null) {
getMapAsync(this);
}
}
#Override
public void onPause() {
super.onPause();
//stop location updates when Activity is no longer active
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
#Override
public void onMapReady(GoogleMap googleMap)
{
mGoogleMap=googleMap;
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
//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) {
//Location Permission already granted
buildGoogleApiClient();
mGoogleMap.setMyLocationEnabled(true);
} else {
//Request Location Permission
checkLocationPermission();
}
}
else {
buildGoogleApiClient();
mGoogleMap.setMyLocationEnabled(true);
}
}
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);
}
}
#Override
public void onConnectionSuspended(int i) {}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {}
#Override
public void onLocationChanged(Location location)
{
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
//Place current location marker
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 = mGoogleMap.addMarker(markerOptions);
//move map camera
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(11));
//optionally, stop location updates if only current location is needed
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
private void checkLocationPermission() {
if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
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.
new AlertDialog.Builder(getActivity())
.setTitle("Location Permission Needed")
.setMessage("This app needs the Location permission, please accept to use location functionality")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(getActivity(),
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION );
}
})
.create()
.show();
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(getActivity(),
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION );
}
}
}
#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, yay! Do the
// location-related task you need to do.
if (ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
mGoogleMap.setMyLocationEnabled(true);
}
} else {
// permission denied, boo! 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
}
}
}
Result
First, the location permission prompt:
Once the user has accepted the permission at runtime, show the user's current location:

Categories

Resources