I have a problem in my project. when i click search bar in top of screen then show an error the error is:
status (statuscode=places_api_access_not_configured resolution=null)
my place api is enabled but I am still getting the error.
Here is my Welcome.java
public class Welcome extends FragmentActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener
{
private GoogleMap mMap;
private static final int MY_PERMISSION_REQUEST_CODE=7000;
private static final int PLAY_SERIVICES_RES_REQUEST=7001;
private LocationRequest mLocationRequest;
private GoogleApiClient mGoogleApiClient;
private Location lastLocation;
private static int UPDATE_INTERVAL=5000;
private static int FATEST_INTERVAL=3000;
private static int DISPLACEMENT=10;
DatabaseReference drivers;
GeoFire geoFire;
Marker mCurrent;
Switch location_switch;
SupportMapFragment mapFragment;
//car animation...
private List<LatLng> polyLineList;
private Marker carMarker;
private float v;
private double lat,lng;
private Handler handler;
private LatLng startPosition,endPosition,currentPosition;
private int index,next;
//private Button btnGo;
private PlaceAutocompleteFragment places;
private String destination;
private PolylineOptions polylineOptions,blackPolylineOptions;
private Polyline blackPolyline,greyPolyline;
private IGoogleAPI mService;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
//init view..
location_switch= findViewById(R.id.location_switch);
location_switch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isOnline) {
if(isOnline)
{
startLocationUpdate();
displayLocation();
Snackbar.make(mapFragment.getView(),"You are Online",Snackbar.LENGTH_SHORT).show();
}
else
{
stopLocationUpdate();
mCurrent.remove();
mMap.clear();
//handler.removeCallbacks(drawPathRunnable);
Snackbar.make(mapFragment.getView(),"You are Offline",Snackbar.LENGTH_SHORT).show();
}
}
});
polyLineList=new ArrayList<>();
//places Api....
places=(PlaceAutocompleteFragment)getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);
places.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
if(location_switch.isChecked())
{
destination=place.getAddress().toString();
destination=destination.replace(" ","+");
getDirection();
}
else {
Toast.makeText(Welcome.this, "Please Change your status in Online", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onError(Status status) {
Toast.makeText(Welcome.this, ""+status.toString(), Toast.LENGTH_SHORT).show();
}
});
//Geo fire
drivers= FirebaseDatabase.getInstance().getReference("Drivers");
geoFire=new GeoFire(drivers);
setUpLocation();
mService= Common.getGoogleAPI();
}
//we request run time permission ,we need override OnRequestPermission Result..
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode)
{
case MY_PERMISSION_REQUEST_CODE:
if(grantResults.length>0&&grantResults[0]==PackageManager.PERMISSION_GRANTED)
{
if(checkPlayServices())
{
buildGoogleApiClient();
createLocationRequest();
if(location_switch.isChecked())
displayLocation();
}
}
}
}
private void setUpLocation() {
if(ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION) !=PackageManager.PERMISSION_GRANTED)
{
//Request Runtime permission...
ActivityCompat.requestPermissions(this,new String[]{
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION
},MY_PERMISSION_REQUEST_CODE);
}
else
{
if(checkPlayServices())
{
buildGoogleApiClient();
createLocationRequest();
if(location_switch.isChecked())
displayLocation();
}
}
}
private void createLocationRequest() {
mLocationRequest=new LocationRequest();
mLocationRequest.setInterval(UPDATE_INTERVAL);
mLocationRequest.setFastestInterval(FATEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
mLocationRequest.setSmallestDisplacement(DISPLACEMENT);
}
private void buildGoogleApiClient() {
mGoogleApiClient=new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect(); //Connected Google api client.....
}
private boolean checkPlayServices() {
int resultCode= GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if(resultCode!=ConnectionResult.SUCCESS)
{
if(GooglePlayServicesUtil.isUserRecoverableError(resultCode))
GooglePlayServicesUtil.getErrorDialog(resultCode,this,PLAY_SERIVICES_RES_REQUEST).show();
else {
Toast.makeText(this, "This device is not supported ", Toast.LENGTH_SHORT).show();
}
return false;
}
return true;
}
private void stopLocationUpdate() {
if(ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION) !=PackageManager.PERMISSION_GRANTED)
{
return;
}
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient,(com.google.android.gms.location.LocationListener) this);
}
private void displayLocation() {
if(ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION) !=PackageManager.PERMISSION_GRANTED)
{
return;
}
lastLocation=LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if(lastLocation!=null)
{
if(location_switch.isChecked())
{
final double latitude=lastLocation.getLatitude();
final double longitude=lastLocation.getLongitude();
//update firebase..
geoFire.setLocation(FirebaseAuth.getInstance().getCurrentUser().getUid(), new GeoLocation(latitude, longitude), new GeoFire.CompletionListener() {
#Override
public void onComplete(String key, DatabaseError error) {
//add marker
if(mCurrent!=null)
mCurrent.remove();//marker remove already
mCurrent=mMap.addMarker(new MarkerOptions()
.position(new LatLng(latitude,longitude))
.title("YOUR LOCATION"));
//Move camera from this position..
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude,longitude),15.0f));
/*//draw animated rotated marker..
rotateMarker(mCurrent,-360,mMap);*/
}
});
}
}
else
{
Log.d("ERROR","Cannot get your location");
}
}
private void rotateMarker(final Marker mCurrent, final float i, GoogleMap mMap) {
final Handler handler=new Handler();
final long start= SystemClock.uptimeMillis();
final float startRotation=mCurrent.getRotation();
final long duration=1500;
final Interpolator interpolator=new LinearInterpolator();
handler.post(new Runnable() {
#Override
public void run() {
long elapsed=SystemClock.uptimeMillis()-start;
float t=interpolator.getInterpolation((float)elapsed/duration);
float rot=t*i+(1-t)*startRotation;
mCurrent.setRotation(-rot>180?rot/2:rot);
if(t<1.0)
{
handler.postDelayed(this,16);
}
}
});
}
private void startLocationUpdate() {
if(ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION) !=PackageManager.PERMISSION_GRANTED)
{
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,mLocationRequest, this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mMap.setTrafficEnabled(false);
mMap.setIndoorEnabled(false);
mMap.setBuildingsEnabled(false);
mMap.getUiSettings().setZoomControlsEnabled(true);
}
#Override
public void onLocationChanged(Location location) {
lastLocation=location;
displayLocation();
}
#Override
public void onConnected(#Nullable Bundle bundle) {
displayLocation();
startLocationUpdate();
}
#Override
public void onConnectionSuspended(int i) {
mGoogleApiClient.connect();
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
}
Hare is my Android Manifest
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.ubarclone">
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="com.google.android.providers.gsf.permisson.READ_GSERVICES" />
<application
android:allowBackup="true"
android:appComponentFactory="whateverString"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme"
tools:replace="android:appComponentFactory">
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="#string/google_maps_key" />
<activity
android:name=".Welcome"
android:label="#string/title_activity_welcome"></activity>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
A screenshot of my issue:
When I click the search bar at the top this error message displays:
Related
I am working on a mobile application and I'm still new to Android Studio. In this app I need to use Google Maps. The app runs fine on my smartphone but when i click the button to navigate to the Google Map page, there is a pop up message that says my app has stopped. Can someone please help me troubleshoot this problem?
MapsActivity.java
public class MapsActivity extends FragmentActivity implements
OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
private GoogleMap mMap;
private GoogleApiClient client;
private LocationRequest locationRequest;
private Location lastlocation;
private Marker currentLocationMarker;
public static final int REQUEST_LOCATION_CODE = 99;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
checkLocationPermission();
}
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
setUpMapIfNeeded();
}
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
//super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch(requestCode)
{
case REQUEST_LOCATION_CODE:
if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
//permission is granted
if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
{
if(client == null)
{
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
}
}
else //permission is denied
{
Toast.makeText(this, "Permission Denied!", Toast.LENGTH_LONG).show();
}
return;
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
{
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
//DO WHATEVER YOU WANT WITH GOOGLEMAP
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
//mMap.setMyLocationEnabled(true);
mMap.setTrafficEnabled(true);
mMap.setIndoorEnabled(true);
mMap.setBuildingsEnabled(true);
mMap.getUiSettings().setZoomControlsEnabled(true);
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
setUpMap();
}
private void setUpMapIfNeeded() {
if (mMap == null) {
SupportMapFragment mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map));
mMap.getMapAsync(this);
if (mMap != null) {
setUpMap();
}
}
}
private void setUpMap() {
mMap.addMarker(new MarkerOptions().position(new LatLng(3.188426, 101.682027)).title("This is my first marker"));
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
//
mMap.setMyLocationEnabled(true); //int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
}
protected synchronized void buildGoogleApiClient()
{
client = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
client.connect();
}
#Override
public void onLocationChanged(Location location) {
// latitude = location.getLatitude();
//longiude = location.getLongitude();
lastlocation = location;
if (currentLocationMarker != null)
{
currentLocationMarker.remove();
}
LatLng latlng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latlng);
markerOptions.title("Current Location");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
currentLocationMarker = mMap.addMarker(markerOptions);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latlng));
mMap.animateCamera(CameraUpdateFactory.zoomBy(10));
if (client != null)
{
LocationServices.FusedLocationApi.removeLocationUpdates(client, this);
}
}
/*#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}*/
public void onClick (View v)
{
if(v.getId() == R.id.searchbtn)
{
EditText userlocation = (EditText)findViewById(R.id.userLocation);
String location = userlocation.getText().toString();
List<Address> addressList = null;
MarkerOptions mo = new MarkerOptions();
if( !location.equals(""))
{
Geocoder geocoder = new Geocoder(this);
try
{
addressList = geocoder.getFromLocationName(location, 5);
}
catch (IOException e)
{
e.printStackTrace();
}
for(int i=0; i<addressList.size(); i++)
{
Address myAddress = addressList.get(i);
LatLng latLng = new LatLng(myAddress.getLatitude(), myAddress.getLongitude());
mo.position(latLng);
mo.title("Your Search Result");
mMap.addMarker(mo);
mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
}
}
}
}
#Override
public void onConnected(#Nullable Bundle bundle) {
locationRequest = new LocationRequest();
locationRequest.setInterval(1000);
locationRequest.setFastestInterval(1000);
locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
{
LocationServices.FusedLocationApi.requestLocationUpdates(client, locationRequest, this);
}
}
public boolean checkLocationPermission()
{
if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
if(ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION))
{
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION_CODE);
}
else
{
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION_CODE);
}
return false;
}
else
return true;
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.asus.autocare">
<!-- To auto-complete the email text field in the login form with the user's
emails -->
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.READ_PROFILE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name =
"com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity" />
<activity android:name=".LoginActivity" />
<activity android:name=".RegisterActivity" />
<activity android:name=".SplashScreen">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="#string/google_maps_key" />
<activity
android:name=".MapsActivity"
android:label="#string/title_activity_maps" />
<activity android:name=".ChooseActivity"></activity>
</application> </manifest>
This is the error that I got:
05-02 21:11:10.236 30445-30445/? E/Zygote: v2
05-02 21:11:10.238 30445-30445/? E/Zygote: accessInfo : 0
05-02 21:11:12.271 30445-30445/com.example.asus.autocare E/BoostFramework:
BoostFramework() : Exception_1 = java.lang.ClassNotFoundException: Didn't
find class "com.qualcomm.qti.Performance" on path:
DexPathList[[],nativeLibraryDirectories=[/system/lib, /vendor/lib]]
05-02 21:11:30.904 30445-30445/com.example.asus.autocare E/AndroidRuntime:
FATAL EXCEPTION: main
Process: com.example.asus.autocare, PID: 30445
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.asus.autocare/com.example.asus.autocare.MapsActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.android.gms.maps.model.Marker com.google.android.gms.maps.GoogleMap.addMarker(com.google.android.gms.maps.model.MarkerOptions)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2984)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3045)
at android.app.ActivityThread.-wrap14(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1642)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6776)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1496)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1386)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.android.gms.maps.model.Marker com.google.android.gms.maps.GoogleMap.addMarker(com.google.android.gms.maps.model.MarkerOptions)' on a null object reference
at com.example.asus.autocare.MapsActivity.setUpMap(MapsActivity.java:147)
at com.example.asus.autocare.MapsActivity.setUpMapIfNeeded(MapsActivity.java:140)
at com.example.asus.autocare.MapsActivity.onCreate(MapsActivity.java:64)
at android.app.Activity.performCreate(Activity.java:6955)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1126)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2927)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3045)
at android.app.ActivityThread.-wrap14(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1642)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6776)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1496)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1386)
Try Moving these lines to onMapLoaded() instead.
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
I'm starting in android, and I want to start strong, I already know a bit of java, so I decided to make a map in android. My doubt is that I try and I do not know what else to do so that when I start my application, I will have the map with the camera addressed to my location. Also I do not know if they can revizar my code, if there is some error or a suggestion, it would be incredible.
public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback, LocationListener {
private GoogleMap mMap;
private DrawerLayout dy;
protected LocationManager locationManager;
protected LocationListener locationListener;
private static final int LOCATION_REQUEST_CODE = 1;
private static final String TAG = MapsActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigation_drawe);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,0, this);
}
public void openNavigatorDrawe(View view){
dy = (DrawerLayout)findViewById(R.id.drawer_layout);
dy.openDrawer(GravityCompat.START);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
UiSettings uiSettings=mMap.getUiSettings();
// uiSettings.setAllGesturesEnabled(false);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
mMap.setMyLocationEnabled(true);
} else {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
} else {
ActivityCompat.requestPermissions(
this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
LOCATION_REQUEST_CODE);
}
}
try {
boolean success = googleMap.setMapStyle(
MapStyleOptions.loadRawResourceStyle(
this, R.raw.liberte));
if (!success) {
Log.e(TAG, "Style parsing failed.");
}
} catch (Resources.NotFoundException e) {
Log.e(TAG, "Can't find style. Error: ", e);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults) {
if (requestCode == LOCATION_REQUEST_CODE) {
// ¿Permisos asignados?
if (permissions.length > 0 &&
permissions[0].equals(Manifest.permission.ACCESS_FINE_LOCATION) &&
grantResults[0] == PackageManager.PERMISSION_GRANTED) {
mMap.setMyLocationEnabled(true);
} else {
Toast.makeText(this, "Error de permisos", Toast.LENGTH_LONG).show();
}
}
}
#Override
public void onLocationChanged(Location location) {
LatLng newloc = new LatLng(location.getLatitude(), location.getLongitude());
mMap.moveCamera(CameraUpdateFactory.newLatLng(newloc));
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
}
I am trying to get my current location using GoogleApiClient and LocationListner. Below is my code which I got from Here.
But the problem is when I start this app in mobile. It is not giving me my current location. I also have checked in debug mode. Latitude and Longitude are not updating in variables. Please check this code and guide me where i am doing wrong or any other logical error. In tutorial developer make a boolean type function named checkLocationPermission(). But this function never used in application. Where should I call that function.
Thanks in advance
Here are my coding files
AndroidManifest.xml
`<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sufian.androidmaps">
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="#string/google_maps_key" />
<activity
android:name=".MapsActivity"
android:label="#string/title_activity_maps">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>`
and My MapsActivity.java File is below
`
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListener
{
private GoogleMap mMap;
GoogleApiClient mGoogleApiClient;
LocationRequest mLocationRequest;
Location mLastLocation;
Marker mCurrLocationMarker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
//mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
//initialize google play services
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
else {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
#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 = mMap.addMarker(markerOptions);
//move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
//stop location updates
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, (com.google.android.gms.location.LocationListener) this);
}
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 100;
public boolean checkLocationPermission(){
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Asking user if explanation is needed
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
return false;
} else {
return true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission was granted.
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
}
} else {
//toast here
}
return;
}
}
}
#Override
public void onConnected(#Nullable Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority
(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi
.requestLocationUpdates(mGoogleApiClient,
mLocationRequest,
(com.google.android.gms.location.
LocationListener) this);
}
}
#Override
public void onConnectionSuspended(int i){
}
The reason your not receiving update locations is because you check if you have location permissions which you don't have before building the Google ApiClient which triggers the location updates.
From Android 6 and higher these aren't granted automatically. But if you call checkLocationPermission() in OnCreate it should prompt the user to grant the permission as soon as you launch the activity
I am trying to use Google Maps on my app. So far I am able to load the map onto a SupportMapFragment which is called onto my MainActivity as a fragment. However, I am unable to see a blue dot despite enabling locations. I am not able to get the latitude or longitude to show up in the logs as well. Can someone help me with this? I am quite lost. Could it be the permissions I have set? I have also added the necessary permissions in the manifest.
This is my code
public class MapFragment extends SupportMapFragment implements LocationListener,OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener{
private GoogleMap googleMap;
private GoogleApiClient googleApiClient;
private LocationRequest locationRequest;
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
Location location;
Marker locationMarker;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
protected synchronized void buildGoogleAPIClient(){
googleApiClient = new GoogleApiClient.Builder(getActivity())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
googleApiClient.connect();
}
#Override
public void onLocationChanged(Location location) {
LatLng currentLocation = new LatLng(location.getLatitude(),location.getLongitude());
Double latitude = currentLocation.latitude;
Double longitude = currentLocation.longitude;
this.location = location;
if(locationMarker!=null){
locationMarker.remove();
}
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(currentLocation);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE));
locationMarker = googleMap.addMarker(markerOptions);
if(googleApiClient!=null){
LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient,this);
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
this.googleMap = googleMap;
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
if(ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)== PackageManager.PERMISSION_GRANTED){
buildGoogleAPIClient();
this.googleMap.setMyLocationEnabled(true);
}else{
checkLocationPermission();
}
}else{
buildGoogleAPIClient();
this.googleMap.setMyLocationEnabled(true);
}
}
#Override
public void onPause() {
super.onPause();
if(googleApiClient!=null){
LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient,this);
}
}
#Override
public void onConnected(#Nullable Bundle bundle) {
locationRequest = new LocationRequest();
locationRequest.setInterval(1000);
locationRequest.setFastestInterval(1000);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
if(ContextCompat.checkSelfPermission(getActivity(),Manifest.permission.ACCESS_FINE_LOCATION)==PackageManager.PERMISSION_GRANTED){
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient,locationRequest,this);
}
}
private void checkLocationPermission(){
if(ContextCompat.checkSelfPermission(getActivity(),Manifest.permission.ACCESS_FINE_LOCATION)!=PackageManager.PERMISSION_GRANTED){
//Ask for permission again once the user sees the explanation
if(ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),Manifest.permission.ACCESS_FINE_LOCATION)){
new AlertDialog.Builder(getActivity())
.setTitle("Location Permission required")
.setMessage("This app requires location permissions in order to function")
.setPositiveButton("Allow", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions(getActivity(),new String[]{Manifest.permission.ACCESS_FINE_LOCATION},MY_PERMISSIONS_REQUEST_LOCATION);
}
})
.create()
.show();
}else{
//No explanation required. Just request for permissions
ActivityCompat.requestPermissions(getActivity(),new String[]{Manifest.permission.ACCESS_FINE_LOCATION},MY_PERMISSIONS_REQUEST_LOCATION);
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode){
case MY_PERMISSIONS_REQUEST_LOCATION: {
if(grantResults.length>0 && grantResults[0]==PackageManager.PERMISSION_GRANTED){
if(googleApiClient==null){
buildGoogleAPIClient();
}
if(ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)== PackageManager.PERMISSION_GRANTED){
this.googleMap.setMyLocationEnabled(true);
}
}else{
Toast.makeText(getActivity(),"Permission denied",Toast.LENGTH_LONG).show();
}
return;
}
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
Hope someone can help me. Thanks
In the code that you are showing you are never calling getMapAsync on your SupportMapFragment so basically you are just showing a map.
Add getMapAsync to your onCreate:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getMapAsync(this);
}
Remember to add the following permissions too:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET"/>
I'm new to android developing, and i'm tring to create an app which gets your coordinates like this tutorial http://developer.android.com/training/location/receive-location-updates.html
but my app crashes. I didn't to the last part "Save the State of the Activity" because i dont know what my LOCATION_KEY or REQUESTING_LOCATION_UPDATES_KEY is.
my code:
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentSender;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.common.SupportErrorDialogFragment;
import java.text.DateFormat;
import java.util.Date;
public class StepCounter extends FragmentActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
// Request code to use when launching the resolution activity
private static final int REQUEST_RESOLVE_ERROR = 1001;
// Unique tag for the error dialog fragment
private static final String DIALOG_ERROR = "dialog_error";
// Bool to track whether the app is already resolving an error
private boolean mResolvingError = false;
//keys
protected final static String REQUESTING_LOCATION_UPDATES_KEY = "requesting-location-updates-key";
protected final static String LOCATION_KEY = "location-key";
protected final static String LAST_UPDATED_TIME_STRING_KEY = "last-updated-time-string-key";
GoogleApiClient mGoogleApiClient;
TextView mLatitudeText;
TextView mLongitudeText;
TextView mcLatitudeText;
TextView mcLongitudeText;
Location mLastLocation;
Location mCurrentLocation;
LocationRequest mLocationRequest;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_step_counter);
mLatitudeText = (TextView) findViewById(R.id.lat);
mLongitudeText = (TextView) findViewById(R.id.lon);
mcLatitudeText = (TextView) findViewById(R.id.llat);
mcLongitudeText = (TextView) findViewById(R.id.llon);
mResolvingError = savedInstanceState != null
&& savedInstanceState.getBoolean(STATE_RESOLVING_ERROR, false);
createLocationRequest();
buildGoogleApiClient();
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
#Override
protected void onStart() {
super.onStart();
if(!mResolvingError)
mGoogleApiClient.connect();
}
#Override
protected void onStop() {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(StepCounter.this);
dialogBuilder.setMessage("onStop");
dialogBuilder.setPositiveButton("Ok", null);
dialogBuilder.show();
mGoogleApiClient.disconnect();
super.onStop();
}
public void onConnected(Bundle connectionHint) {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
mCurrentLocation = mLastLocation;
if (mLastLocation != null) {
mLatitudeText.setText(String.valueOf(mLastLocation.getLatitude()));
mLongitudeText.setText(String.valueOf(mLastLocation.getLongitude()));
}
//modified
startLocationUpdates();
}
//pana aici merge de aici vine partea cu update
protected void startLocationUpdates() {
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
}
protected void createLocationRequest() {
LocationRequest mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(10000);
mLocationRequest.setFastestInterval(5000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
#Override
public void onLocationChanged(Location location) {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(StepCounter.this);
dialogBuilder.setMessage("onLocationChanged");
dialogBuilder.setPositiveButton("Ok", null);
dialogBuilder.show();
mLastLocation = mCurrentLocation;
mCurrentLocation = location;
updateUI();
}
public void updateUI()
{
mLatitudeText.setText(String.valueOf(mLastLocation.getLatitude()));
mLongitudeText.setText(String.valueOf(mLastLocation.getLongitude()));
mcLatitudeText.setText(String.valueOf(mCurrentLocation.getLatitude()));
mcLongitudeText.setText(String.valueOf(mCurrentLocation.getLongitude()));
}
#Override
protected void onPause() {
super.onPause();
stopLocationUpdates();
}
protected void stopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(
mGoogleApiClient, this);
}
#Override
public void onResume() {
super.onResume();
if (mGoogleApiClient.isConnected()) {
startLocationUpdates();
}
}
// De aici partea cu rezolvatu problemei
#Override
public void onConnectionSuspended(int i) {
//todo nust...
}
#Override
public void onConnectionFailed(ConnectionResult result) {
if (mResolvingError) {
// Already attempting to resolve an error.
return;
} else if (result.hasResolution()) {
try {
mResolvingError = true;
result.startResolutionForResult(this, REQUEST_RESOLVE_ERROR);
} catch (IntentSender.SendIntentException e) {
// There was an error with the resolution intent. Try again.
mGoogleApiClient.connect();
}
} else {
// Show dialog using GoogleApiAvailability.getErrorDialog()
showErrorDialog(result.getErrorCode());
mResolvingError = true;
}
}
// The rest of this code is all about building the error dialog
/* Creates a dialog for an error message */
private void showErrorDialog(int errorCode) {
// Create a fragment for the error dialog
ErrorDialogFragment dialogFragment = new ErrorDialogFragment();
// Pass the error that should be displayed
Bundle args = new Bundle();
args.putInt(DIALOG_ERROR, errorCode);
dialogFragment.setArguments(args);
dialogFragment.show(getFragmentManager(), "errordialog");
}
/* Called from ErrorDialogFragment when the dialog is dismissed. */
public void onDialogDismissed() {
mResolvingError = false;
}
/* A fragment to display an error dialog */
public static class ErrorDialogFragment extends DialogFragment {
public ErrorDialogFragment() { }
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Get the error code and retrieve the appropriate dialog
int errorCode = this.getArguments().getInt(DIALOG_ERROR);
return GoogleApiAvailability.getInstance().getErrorDialog(
this.getActivity(), errorCode, REQUEST_RESOLVE_ERROR);
}
#Override
public void onDismiss(DialogInterface dialog) {
((StepCounter) getActivity()).onDialogDismissed();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_RESOLVE_ERROR) {
mResolvingError = false;
if (resultCode == RESULT_OK) {
// Make sure the app is not already connected or attempting to connect
if (!mGoogleApiClient.isConnecting() &&
!mGoogleApiClient.isConnected()) {
mGoogleApiClient.connect();
}
}
}
}
private static final String STATE_RESOLVING_ERROR = "resolving_error";
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(STATE_RESOLVING_ERROR, mResolvingError);
}
}
And this is my manifest:
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
//android:theme="#android:style/Theme.Holo"
<activity
android:name=".LoginScreen"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".Register"
android:label="#string/title_activity_register" >
</activity>
<activity
android:name=".MainActivity"
android:label="#string/title_activity_main" >
</activity>
<activity
android:name=".StepCounter"
android:label="#string/title_activity_step_counter" >
</activity>
</application>
When i run my app with the emulator (which doesn't have google services) and i click the update google services i get this error (i don't think this is the problem because i have google services on my phone) :
08-26 09:54:24.640 7191-7191/com.persasrl.paul.quickfit E/SettingsRedirect﹕ Can't redirect to app settings for Google Play services
08-26 09:54:24.653 7191-7191/com.persasrl.paul.quickfit D/AndroidRuntime﹕ Shutting down VM
08-26 09:54:24.654 7191-7191/com.persasrl.paul.quickfit E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.persasrl.paul.quickfit, PID: 7191
java.lang.RuntimeException: Unable to pause activity {com.persasrl.paul.quickfit/com.persasrl.paul.quickfit.StepCounter}: java.lang.IllegalStateException: GoogleApiClient is not connected yet.
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3613)
at android.app.ActivityThread.access$1300(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1352)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.IllegalStateException: GoogleApiClient is not connected yet.
at com.google.android.gms.common.api.zzf.zzb(Unknown Source)
at com.google.android.gms.common.api.zzg.zzb(Unknown Source)
at com.google.android.gms.location.internal.zzd.removeLocationUpdates(Unknown Source)
at com.persasrl.paul.quickfit.StepCounter.stopLocationUpdates(StepCounter.java:148)
at com.persasrl.paul.quickfit.StepCounter.onPause(StepCounter.java:144)
at android.app.Activity.performPause(Activity.java:6101)
at android.app.Instrumentation.callActivityOnPause(Instrumentation.java:1310)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3603)
I tried to delete the startLocationUpdates part and it doesn't crash anymore... but also it doesn't update location...
SOLVED IT
so the problem was that i declared mLocationRequest twice at the start of the project:
LocationRequest mLocationRequest;
and in
createLocationRequest()
LocationRequest mLocationRequest = new LocationRequest();
i changed in crateLocationRequest LocationRequest mLocationRequest = new LocationRequest(); to mLocationRequest = new LocationRequest(); and now it doesn't crash.