How can i get Current location.i have tried below code but getting null for location-
public class LocationsMapView extends Fragment implements LocationListener, android.location.LocationListener{
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
locationManager = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,0,0,LocationsMapView.this);
// Define the criteria how to select the locatioin provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
} else {
System.out.println("Location not available");
}
}
#Override
public void onLocationChanged(Location loc) {
current=new LatLng(loc.getLatitude(),loc.getLongitude());
lat=loc.getLatitude();longi=loc.getLongitude();
Toast.makeText(getActivity(), "location-"+loc.getLatitude(), Toast.LENGTH_SHORT).show();
System.out.println("location.."+lat+"..."+longi+" current .."+current);
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
#Override
public void onResume() {
// TODO Auto-generated method stub
super.onResume();
location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
} else {
System.out.println("Location not available");
}
}
}
I have also given permission in manifest-
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Try on this way:
public static class XYZ extends Fragment
implements
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener,
LocationListener {
GoogleMap map;
LatLng latlng;
private LocationRequest lr;
private LocationClient lc;
MapFragment mapFragment;
ImageView iv;
private static View view;
public XYZ() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (view != null) {
ViewGroup parent = (ViewGroup) view.getParent();
if (parent != null)
parent.removeView(view);
}
try {
view = inflater.inflate(R.layout.XYZ, container,
false);
mapFragment = ((MapFragment) this.getActivity()
.getFragmentManager().findFragmentById(R.id.map));
iv = (ImageView) view.findViewById(R.id.iv);
map = mapFragment.getMap();
map.getUiSettings().setAllGesturesEnabled(false);
map.getUiSettings().setMyLocationButtonEnabled(false);
map.setMyLocationEnabled(true);
map.getUiSettings().setZoomControlsEnabled(false);
MapsInitializer.initialize(this.getActivity());
} catch (GooglePlayServicesNotAvailableException e) {
Toast.makeText(getActivity(), "Google Play Services missing !",
Toast.LENGTH_LONG).show();
} catch (InflateException e) {
Toast.makeText(getActivity(), "Problems inflating the view !",
Toast.LENGTH_LONG).show();
} catch (NullPointerException e) {
Toast.makeText(getActivity(), "Google Play Services missing !",
Toast.LENGTH_LONG).show();
}
return view;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
lr = LocationRequest.create();
lr.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
lc = new LocationClient(this.getActivity().getApplicationContext(),
this, this);
lc.connect();
}
#Override
public void onLocationChanged(Location l2) {
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(
new LatLng(l2.getLatitude(), l2.getLongitude()), 15);
map.animateCamera(cameraUpdate);
}
#Override
public void onConnectionFailed(ConnectionResult arg0) {
}
#Override
public void onConnected(Bundle connectionHint) {
lc.requestLocationUpdates(lr, this);
}
#Override
public void onDisconnected() {
}
}
This is perfect working in my case.
Related
i want to access current location in fragments , but i am using API 28 and android version 3.2.1. i try everything from internet follow tutorials but i cant access my current location , there is no error in my code but i don't know why i cant access it. when i run my program i just see google default map, no marker etc.
i want to access my location through network provider as well as gps provider if network provider is not available.
i also add permissions in manifest
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
for a permission access i am using library from github and for lacation and map
implementation 'pub.devrel:easypermissions:2.0.0'
implementation 'com.google.android.gms:play-services-maps:16.0.0'
implementation 'com.google.android.gms:play-services-location:16.0.0'
please check my code and guide me how i can access current location my code is in below in my code there is also step counter code but ignore that one.
here is my code
public class HomeActivity extends Fragment implements SensorEventListener, OnMapReadyCallback {
SensorManager sensorManager;
TextView set_steps;
TextView set_calories;
TextView set_distance;
boolean running = false;
private static int steps;
private static int calories;
private static double distance;
private GoogleMap mMap;
LocationManager locationManager;
public static final int Request_User_Location_Code = 99;
GoogleApiClient googleApiClient;
private LocationRequest locationRequest;
private Location lastLocation;
private Marker currentUserLocationMarker;
private final int REQUEST_LOCATION_PERMISSION = 1;
Provider provider;
View view;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.activity_home, container, false);
requestLocationPermission();
stepsCounter();
locationTracker();
return view;
}
void stepsCounter() {
set_steps = (TextView) view.findViewById(R.id.set_steps);
set_calories = (TextView) view.findViewById(R.id.set_calories);
set_distance = (TextView) view.findViewById(R.id.set_distance);
sensorManager = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE);
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onResume() {
super.onResume();
running = true;
Sensor countSensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
if (countSensor != null) {
sensorManager.registerListener((SensorEventListener) getActivity(), countSensor, SensorManager.SENSOR_DELAY_UI);
} else {
Toast.makeText(getActivity(), "Sensor not Found", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onPause() {
super.onPause();
running = false;
}
#Override
public void onSensorChanged(SensorEvent event) {
if (running) {
steps = (int) event.values[0];
set_steps.setText(steps + "");
caloriesCounter();
distanceCover();
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
void caloriesCounter() {
calories = steps / 20;
set_calories.setText(calories + "");
}
void distanceCover() {
distance = (double) steps * 0.76;
String distanceText = Double.toString(distance);
set_distance.setText(distanceText);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
}
void locationTracker() {
SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
if ((ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) && (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
}
if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, new LocationListener() {
#Override
public void onLocationChanged(Location location) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng latLng= new LatLng(latitude,longitude);
Geocoder geocoder=new Geocoder(getActivity().getApplicationContext());
try {
List<Address> addressList = geocoder.getFromLocation(latitude,longitude,1);
String str = addressList.get(0).getLocality()+",";
str+= addressList.get(0).getCountryName();
mMap.addMarker(new MarkerOptions().position(latLng).title(str));
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
});
} else if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new LocationListener() {
#Override
public void onLocationChanged(Location location) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng latLng= new LatLng(latitude,longitude);
Geocoder geocoder=new Geocoder(getActivity().getApplicationContext());
try {
List<Address> addressList = geocoder.getFromLocation(latitude,longitude,1);
String str = addressList.get(0).getLocality()+",";
str+= addressList.get(0).getCountryName();
mMap.addMarker(new MarkerOptions().position(latLng).title(str));
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
});
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
// Forward results to EasyPermissions
EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
}
#AfterPermissionGranted(REQUEST_LOCATION_PERMISSION)
public void requestLocationPermission() {
String[] perms = {Manifest.permission.ACCESS_FINE_LOCATION};
if(EasyPermissions.hasPermissions(getActivity(), perms)) {
// Toast.makeText(getActivity(), "Permission already granted", Toast.LENGTH_SHORT).show();
}
else {
EasyPermissions.requestPermissions(this, "Please grant the location permission", REQUEST_LOCATION_PERMISSION, perms);
}
}
}
but remember i am using ApI 28
I think there is a problem in My Location Listener but I am not able to pinpoint it. When I remove the code to get GPS my application is working fine.
public class RescueFragment extends Fragment{
public RescueFragment(){}
private static final long mindisch=1;
private static final long mintim=1000;
protected LocationManager locationManager;
protected Double latitude,longitude;
TextView alert_display;
Button btn;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_rescue, container, false);
alert_display = (TextView)rootView.findViewById(R.id.alert_display);
btn = (Button) rootView.findViewById(R.id.button_rescue_me);
locationManager =(LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,mindisch,mintim, new MyLocationListener() );
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
alert_display.setText("Alert Sent to User");
showCurrentLocation();
}
});
return rootView;
}
protected void showCurrentLocation()
{
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location!=null)
{
latitude=location.getLatitude();
longitude=location.getLongitude();
Toast.makeText(getActivity(), "Alert sent. Location: "+ latitude+" "+ longitude, Toast.LENGTH_LONG).show();
}
}
private class MyLocationListener implements LocationListener{
#Override
public void onLocationChanged(Location location) {
latitude=location.getLatitude();
longitude=location.getLongitude();
Toast.makeText(getActivity(), "Alert sent. Location: "+ latitude+" "+ longitude, Toast.LENGTH_LONG).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Toast.makeText(getActivity(), "Provider Status Changed: ", Toast.LENGTH_LONG).show();
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(getActivity(), "GPS ON", Toast.LENGTH_LONG).show();
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(getActivity(), "GPS OFF:", Toast.LENGTH_LONG).show();
}
}
}
Add this Permissions in your Manifest.
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
For Android Versions 6.0 you need to allow user's to give Runtime Permissions.
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) ==
PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) ==
PackageManager.PERMISSION_GRANTED) {
googleMap.setMyLocationEnabled(true);
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
} else {
Toast.makeText(this, R.string.error_permission_map, Toast.LENGTH_LONG).show();
}
Fatal Exception: java.lang.RuntimeException
Unable to destroy activity : java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
problem is Samsung SM G355H and micromax A106
Here is my code
public class EnRouteFragment extends Fragment implements LocationListener{
View rootView;
LayoutInflater inflater;
ViewGroup container;
Context context;
private GoogleMap googleMap;
// flag for GPS status
boolean isGPSEnabled = false;
boolean canGetLocation = false;
// flag for network status
boolean isNetworkEnabled = false;
Location location; // location
Double dblIntLat=null; // latitude
Double dblIntLog=null; // longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 0; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 0; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
MarkerOptions dynamicMarker;
Marker markerCurre;
public EnRouteFragment()
{
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
final Bundle savedInstanceState) {
// TODO Auto-generated method stub
this.inflater = inflater;
this.container = container;
initializeVariables();
initializeUIVariables();
initializeListeners();
attachEventListeners();
return rootView;
}
#Override
public void initializeVariables() {
// TODO Auto-generated method stub
context=getActivity();
if (rootView != null) {
ViewGroup parent = (ViewGroup) rootView.getParent();
if (parent != null)
parent.removeView(rootView);
}
try {
rootView = inflater.inflate(R.layout.fragment_enroute_marchent, container, false);
} catch (InflateException e) {
/* map is already there, just return view as it is */
}
}
#Override
public void initializeUIVariables() {
// TODO Auto-generated method stub
}
#Override
public void initializeListeners() {
// TODO Auto-generated method stub
}
#Override
public void attachEventListeners() {
// TODO Auto-generated method stub
}
// ------------------------------------fetch lat long from GPS OR NETWORK provider-------
public Location getLocation() {
try {
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
// First get location from Network Provider
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
dblIntLat = location.getLatitude();
dblIntLog = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,MIN_TIME_BW_UPDATES,MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
dblIntLat = location.getLatitude();
dblIntLog = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
// -----------------------------------------end---------------
// --------------------------------------initialize google map---------------
private void initilizeMap() {
if (googleMap == null) {
System.out.println("--------- initilizeMap() if");
googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.enroute_map)).getMap();
googleMap.setMyLocationEnabled(true);
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
googleMap.getUiSettings().setRotateGesturesEnabled(false);
googleMap.getUiSettings().setZoomControlsEnabled(true);
if(dblIntLat!=null && dblIntLog !=null)
{
markerCurre = googleMap.addMarker(new MarkerOptions().position(
new LatLng(dblIntLat, dblIntLog)).icon(BitmapDescriptorFactory.fromResource(R.drawable.bike)));
}
if(dblIntLat!=null && dblIntLog !=null)
{
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(dblIntLat,dblIntLog) , 12.0f) );
}
if (googleMap == null) {
Toast.makeText(context,
"Sorry! unable to create maps", Toast.LENGTH_SHORT)
.show();
}
}
else
{
System.out.println("--------- initilizeMap() else");
if(markerCurre!=null)
{
markerCurre.remove();
}
if(dblIntLat!=null && dblIntLog !=null)
{
markerCurre = googleMap.addMarker(new MarkerOptions().position(
new LatLng(dblIntLat, dblIntLog)).icon(BitmapDescriptorFactory.fromResource(R.drawable.bike)));
}
}
}
#Override
public void onLocationChanged(Location loc) {
// TODO Auto-generated method stub
dblIntLat = loc.getLatitude();
dblIntLog = loc.getLongitude();
initilizeMap();
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
#Override
public void onDestroyView() {
// TODO Auto-generated method stub
super.onDestroyView();
Fragment fragment = getFragmentManager().findFragmentById(R.id.enroute_map);
if(fragment!=null)
{
FragmentTransaction ft = getActivity().getFragmentManager().beginTransaction();
ft.remove(fragment);
ft.commitAllowingStateLoss();
}
}
#Override
public void onPause() {
super.onPause();
if(locationManager!=null)
{
locationManager.removeUpdates(this);
}
}
#Override
public void onResume() {
super.onResume();
getLocation();
}
#Override
public void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
//super.onSaveInstanceState(outState);
}
}
here is the error log cat
java.lang.RuntimeException: Unable to destroy activity : java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
at android.app.ActivityThread.performDestroyActivity(ActivityThread.java:3733)
at android.app.ActivityThread.handleDestroyActivity(ActivityThread.java:3751)
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3951)
at android.app.ActivityThread.access$1000(ActivityThread.java:166)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1287)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5511)
at java.lang.reflect.Method.invokeNative(Method.java)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
at dalvik.system.NativeStart.main(NativeStart.java)
Caused by: java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
at android.app.FragmentManagerImpl.checkStateLoss(FragmentManager.java:1323)
at android.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1341)
at android.app.BackStackRecord.commitInternal(BackStackRecord.java:597)
at android.app.BackStackRecord.commit(BackStackRecord.java:575)
at com.matrix.hungerz.EnRouteFragment.onDestroyView(EnRouteFragment.java:744)
at android.app.Fragment.performDestroyView(Fragment.java:1898)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:954)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1062)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1044)
at android.app.FragmentManagerImpl.dispatchDestroy(FragmentManager.java:1887)
at android.app.Activity.performDestroy(Activity.java:5493)
at android.app.Instrumentation.callActivityOnDestroy(Instrumentation.java:1123)
at android.app.ActivityThread.performDestroyActivity(ActivityThread.java:3720)
at android.app.ActivityThread.handleDestroyActivity(ActivityThread.java:3751)
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3951)
at android.app.ActivityThread.access$1000(ActivityThread.java:166)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1287)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5511)
at java.lang.reflect.Method.invokeNative(Method.java)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
at dalvik.system.NativeStart.main(NativeStart.java)
This logcat error doesn't correspond to the code you've provided.
Note this line in the logcat:
android.app.BackStackRecord.commit(BackStackRecord.java:575)
This means that the error was caused by a call to FragmentTransaction.commit(), but your code suggests that you call FragmentTransaction.commitAllowingStateLoss().
I can think of three possible reasons:
You are looking at the wrong part of the code
You previously had commit() in place of commitAllowingStateLoss(), and the errors happen on the older version of your app
Your code has been run on a custom ROM that screwed up parts of AOSP code (see below).
The relevant parts of AOSP code:
From BackStackRecord:
public int commit() {
return commitInternal(false);
}
public int commitAllowingStateLoss() {
return commitInternal(true);
}
int commitInternal(boolean allowStateLoss) {
if (mCommitted) {
throw new IllegalStateException("commit already called");
}
...
mManager.enqueueAction(this, allowStateLoss);
return mIndex;
}
From FragmentManagerImpl:
public void enqueueAction(Runnable action, boolean allowStateLoss) {
if (!allowStateLoss) {
checkStateLoss();
}
...
}
private void checkStateLoss() {
if (mStateSaved) {
throw new IllegalStateException(
"Can not perform this action after onSaveInstanceState");
}
if (mNoTransactionsBecause != null) {
throw new IllegalStateException(
"Can not perform this action inside of " + mNoTransactionsBecause);
}
}
This is my code i want to plot multiple marker in google map
when i write mapview.getoverlay().add(overlaymarker) it is not working
i am not use MapActivity i use fragment so this is not supported getoverlays() please help me.......
fragmnt1.java
public class one extends Fragment implements LocationListener {
MapView mapView;
GoogleMap googleMap;
private boolean mapsSupported = true;
Location location;
double latitude; // latitude
double longitude;
LatLng latlang;
LocationManager manager;
Overlay_Marker overmarker;
frag provider;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final RelativeLayout parent = (RelativeLayout) inflater.inflate(R.layout.one, container, false);
mapView = (MapView) parent.findViewById(R.id.map);
provider=new frag(getActivity());
Log.d("spn", "oncreate view");
return parent;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
MapsInitializer.initialize(getActivity());
} catch (Exception ex) {
mapsSupported = false;
}
if (mapView != null) {
mapView.onCreate(savedInstanceState);
}
initializeMap();
Log.d("spn", "onactivity created");
}
private void initializeMap() {
if (googleMap == null && mapsSupported) {
mapView = (MapView) getActivity().findViewById(R.id.map);
googleMap = mapView.getMap();
Drawable dmarker=getResources().getDrawable(R.drawable.ic_launcher);
dmarker.setBounds(0, 0, dmarker.getIntrinsicWidth(), dmarker.getIntrinsicHeight());
overmarker=new Overlay_Marker(dmarker,getActivity());
Drawable windmill = getResources().getDrawable(R.drawable.ic_launcher);
Drawable bigBen = getResources().getDrawable(R.drawable.ic_launcher);
Drawable eiffelTower = getResources().getDrawable(R.drawable.ic_launcher);
overmarker.addOverlayItem(52372991, 4892655, "Amsterdam", windmill);
overmarker.addOverlayItem(51501851, -140623, "London", bigBen);
overmarker.addOverlayItem(48857522, 2294496, "Paris", eiffelTower);
//List<Overlay_Marker> temp = (List<Overlay_Marker>) mapView.getOverlay();
// temp.add(overmarker);
mapView.getOverlay().add(overmarker); /// Not working
GetLongitude_Latitude();
}
}
public void GetLongitude_Latitude()
{
manager=(LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
location=provider.getLocation(LocationManager.NETWORK_PROVIDER);
Criteria criteria = new Criteria();
// Getting the name of the provider that meets the criteria
String provider = manager.getBestProvider(criteria, false);
if(provider!=null && !provider.equals("")){
// Get the location from the given provider
Location location = manager.getLastKnownLocation(provider);
manager.requestLocationUpdates(provider, 20000, 1, this);
if(location!=null)
onLocationChanged(location);
// Toast.makeText(getActivity(), "Location retrieved"+location.getLatitude()+" and "+location.getLongitude(), Toast.LENGTH_SHORT).show();
//else
// Toast.makeText(getActivity(), "Location can't be retrieved", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getActivity(), "No Provider Found", Toast.LENGTH_SHORT).show();
}
Log.d("spn", "location"+location);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
#Override
public void onResume() {
super.onResume();
mapView.onResume();
initializeMap();
}
#Override
public void onPause() {
super.onPause();
mapView.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
#Override
public void onLocationChanged(Location location) {
latitude=location.getLatitude();
longitude=location.getLongitude();
latlang=new LatLng(latitude, longitude);
MarkerOptions marker=new MarkerOptions().position(latlang);
googleMap.addMarker(marker);
googleMap.setMyLocationEnabled(true);
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
googleMap.getUiSettings().setZoomGesturesEnabled(true);
googleMap.getUiSettings().setZoomControlsEnabled(true);
googleMap.getUiSettings().setCompassEnabled(true);
googleMap.getUiSettings().setRotateGesturesEnabled(true);
CameraPosition cameraPosition = new CameraPosition.Builder().target(
latlang).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
}
I have a problem with the SupportMapFragment and moving the camera to a location on the map.
public class MapPositionFragment extends SupportMapFragment implements LocationListener{
private GoogleMap map = null;
private Button lockButton = null;
private Location currentLocation = null;
private LocationManager locationManager = null;
private View mapView = null;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mapView = super.onCreateView(inflater, container, savedInstanceState);
View v = inflater.inflate(R.layout.fragment_route_map, container, false);
SetUpMap(v);
return v;
}
#Override
public void onResume() {
// TODO Auto-generated method stub
super.onResume();
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
if (isVisibleToUser){
SetUpLocationService();
}
}
private void SetUpLockButton(){
lockButton = (Button)getActivity().findViewById(R.id.lock_screen_button);
lockButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
ToggleLockButton();
}
});
}
private void ToggleLockButton(){
BaseSwipeActivity baseActivity = (BaseSwipeActivity)getActivity();
boolean swipeEnabled = baseActivity.TogglePaging();
if (swipeEnabled){
lockButton.setBackgroundResource(R.drawable.stock_lock_open);
}
else{
lockButton.setBackgroundResource(R.drawable.stock_lock);
}
}
private void SetUpLocationService(){
boolean gpsIsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
boolean networkIsEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (networkIsEnabled){
// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
} else if (gpsIsEnabled){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
}
private void SetCurrentLocation(final Location location){
if (map != null){
getActivity().runOnUiThread(new Runnable() {
public void run() {
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 10);
map.moveCamera(cameraUpdate);
}
});
}
}
private void SetUpMap(View view) {
if (map == null){
getActivity().runOnUiThread(new Runnable() {
public void run() {
map = getMap();
map.getUiSettings().setMyLocationButtonEnabled(true);
map.setIndoorEnabled(true);
map.getUiSettings().setZoomControlsEnabled(false);
locationManager = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
}
});
}
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
SetUpLockButton();
}
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
SetCurrentLocation(location);
}
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
}
It's SupportMapFragment which is positioned inside a ViewPager. The map is shown, but I cannot change the map settings and i'm not able to change the camera position. I thought maybe because it's in a other thread I have to use the UI Thread, but that doesn't change anything.
So maybe someone has an idea, it would be great!
thx Manuel
I encountered the same problem today. Here's my solution for it.
As you had:
// # SetUpMap()
map = getMap();
Replace it with:
// Remeber to change the map id (R.id.map) to what you have in the layout .xml
map = ((SupportMapFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
Seems like this solution doesn't work with Android support library 21.0.x (I have tested for .2 and .3). As this method works with older Android support libraries there might be a bug etc.