NullPointerException when trying to check permissions - java

I'm trying to check if the user has android.Manifest.permission.ACCESS_FINE_LOCATION enabled. When running the application, I get a NullPointerException error.
package dtt.romano.rsrpechhulp;
import android.app.Activity;
import android.content.Context;
import android.content.IntentSender;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
public class LocationProvider extends MainActivity implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,LocationListener {
public abstract interface LocationCallback {
public void handleNewLocation(Location location);
}
public static final String TAG = LocationProvider.class.getSimpleName();
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
private LocationCallback mLocationCallback;
private Context mContext;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
public LocationProvider(Context context, LocationCallback callback) {
mGoogleApiClient = new GoogleApiClient.Builder(context)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mLocationCallback = callback;
// Create the LocationRequest object
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(10 * 1000) // 10 seconds, in milliseconds
.setFastestInterval(1 * 1000); // 1 second, in milliseconds
mContext = context;
}
public void connect() {
mGoogleApiClient.connect();
}
public void disconnect() {
if (mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
mGoogleApiClient.disconnect();
}
}
public void locationUpdate(){
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{
android.Manifest.permission.ACCESS_FINE_LOCATION
}, 10);
}else{
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (location == null) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
else {
mLocationCallback.handleNewLocation(location);
}
}
}
#Override
public void onConnected(Bundle bundle) {
Log.i(TAG, "Location services connected.");
locationUpdate();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case 10:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
locationUpdate();
}
return;
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
/*
* Google Play services can resolve some errors it detects.
* If the error has a resolution, try sending an Intent to
* start a Google Play services activity that can resolve
* error.
*/
if (connectionResult.hasResolution() && mContext instanceof Activity) {
try {
Activity activity = (Activity)mContext;
// Start an Activity that tries to resolve the error
connectionResult.startResolutionForResult(activity, CONNECTION_FAILURE_RESOLUTION_REQUEST);
/*
* Thrown if Google Play services canceled the original
* PendingIntent
*/
} catch (IntentSender.SendIntentException e) {
// Log the error
e.printStackTrace();
}
} else {
/*
* If no resolution is available, display a dialog to the
* user with the error.
*/
Log.i(TAG, "Location services connection failed with code " + connectionResult.getErrorCode());
}
}
#Override
public void onLocationChanged(Location location) {
mLocationCallback.handleNewLocation(location);
}
}
Here is the error log:
java.lang.NullPointerException: Attempt to invoke virtual method 'int android.content.Context.checkPermission(java.lang.String, int, int)' on a null object reference
at android.content.ContextWrapper.checkPermission(ContextWrapper.java:637)
at android.support.v4.content.ContextCompat.checkSelfPermission(ContextCompat.java:387)
at dtt.romano.rsrpechhulp.LocationProvider.onConnected(LocationProvider.java:68)
at com.google.android.gms.common.internal.zzk.zzk(Unknown Source)
at com.google.android.gms.common.api.internal.zzj.zzi(Unknown Source)
at com.google.android.gms.common.api.internal.zzh.zzpx(Unknown Source)
at com.google.android.gms.common.api.internal.zzh.onConnected(Unknown Source)
at com.google.android.gms.common.api.internal.zzl.onConnected(Unknown Source)
at com.google.android.gms.common.api.internal.zzc.onConnected(Unknown Source)
at com.google.android.gms.common.internal.zzj$zzg.zzqL(Unknown Source)
at com.google.android.gms.common.internal.zzj$zza.zzc(Unknown Source)
at com.google.android.gms.common.internal.zzj$zza.zzw(Unknown Source)
at com.google.android.gms.common.internal.zzj$zzc.zzqN(Unknown Source)
at com.google.android.gms.common.internal.zzj$zzb.handleMessage(Unknown Source)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

if (ActivityCompat.checkSelfPermission((Activity)mContext, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions((Activity)mContext, new String[]{
android.Manifest.permission.ACCESS_FINE_LOCATION
}, 10);
}
Try to use (Activity)mContext instead of this. it may help.

if (ActivityCompat.checkSelfPermission(ActivityName.this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(ActivityName.this, new String[]{
android.Manifest.permission.ACCESS_FINE_LOCATION
}, 10);
}
Try with your ActivityName.this

Related

Get current user location- Android

I know there are a lot of examples on the internet about this subject but my problem isn't the code, is the part where I get the location. The FusedLocationProviderClient.getLastLocation() always returns null when I don't open Google Maps before. To get my current location I have to open google maps to get my current location and after that my app can know the location. My question is: is there a way to track my current location without opening google maps before? Here is what I tried:
package com.example.gps;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.tasks.OnSuccessListener;
import java.io.IOException;
import java.util.List;
public class MainActivity extends AppCompatActivity {
public static final int DEFAULT_UPDATE_INTERVAL = 30;
public static final int FAST_UPDATE_INTERVAL = 5;
public static final int PERMISSIONS_FINE_LOCATION = 99;
TextView tv_lat, tv_lon, tv_altitude,
tv_accuracy, tv_speed, tv_sensor, tv_updates, tv_address;
Switch sw_locationupdates, sw_gps;
// Google API for location services.
FusedLocationProviderClient fusedLocationProviderClient;
// Location request config file for all settings related to FusedLocationProviderClient
LocationRequest locationRequest;
LocationCallback locationCallBack;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv_lat = findViewById(R.id.tv_lat);
tv_lon = findViewById(R.id.tv_lon);
tv_altitude = findViewById(R.id.tv_altitude);
tv_accuracy = findViewById(R.id.tv_accuracy);
tv_speed = findViewById(R.id.tv_speed);
tv_sensor = findViewById(R.id.tv_sensor);
tv_updates = findViewById(R.id.tv_updates);
tv_address = findViewById(R.id.tv_address);
sw_gps = findViewById(R.id.sw_gps);
sw_locationupdates = findViewById(R.id.sw_locationsupdates);
locationRequest = new LocationRequest();
locationRequest.setInterval(1000 * DEFAULT_UPDATE_INTERVAL);
locationRequest.setFastestInterval(1000 * FAST_UPDATE_INTERVAL);
locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
locationCallBack = new LocationCallback() {
#Override
public void onLocationResult(#NonNull LocationResult locationResult) {
super.onLocationResult(locationResult);
updateUIValues(locationResult.getLastLocation());
}
};
sw_locationupdates.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (sw_locationupdates.isChecked()) {
startLocationUpdates();
} else {
stopLocationUpdates();
}
}
});
sw_gps.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (sw_gps.isChecked()) {
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
String text = "Using GPS sensors";
tv_sensor.setText(text);
} else {
locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
String text = "Using Towers + WIFi";
tv_sensor.setText(text);
}
}
});
updateGPS();
}// end onCreate
private void stopLocationUpdates() {
String text = "Location is NOT being tracked";
tv_updates.setText(text);
Toast.makeText(this, "done", Toast.LENGTH_SHORT).show();
fusedLocationProviderClient.removeLocationUpdates(locationCallBack);
}
private void startLocationUpdates() {
String text = "Location is being tracked";
tv_updates.setText(text);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "a", Toast.LENGTH_SHORT).show();
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
// requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION,
// Manifest.permission.ACCESS_COARSE_LOCATION},
PERMISSIONS_FINE_LOCATION);
// return;
}
fusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallBack, null);
updateGPS();
Toast.makeText(this, "tracking again", Toast.LENGTH_SHORT).show();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case PERMISSIONS_FINE_LOCATION:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
updateGPS();
} else {
Toast.makeText(this, "This app requires permission to be granted in order to work properly", Toast.LENGTH_SHORT).show();
finish();
}
}
}
private void updateGPS() {
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(MainActivity.this);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
fusedLocationProviderClient.getLastLocation().addOnSuccessListener(this, new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
updateUIValues(location);
}
});
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSIONS_FINE_LOCATION);
}
}
}
private void updateUIValues(Location location) {
if (location != null) {
tv_lat.setText(String.valueOf(location.getLatitude()));
tv_lon.setText(String.valueOf(location.getLongitude()));
tv_accuracy.setText(String.valueOf(location.getAccuracy()));
if (location.hasAltitude()) {
tv_altitude.setText(String.valueOf(location.getAltitude()));
} else {
String text = "Not available- altitude";
tv_altitude.setText(text);
}
if (location.hasSpeed()) {
tv_speed.setText(String.valueOf(location.getSpeed()));
} else {
String text = "Not available- speed";
tv_speed.setText(text);
}
Geocoder geocoder = new Geocoder(MainActivity.this);
try {
List<Address> addressList = geocoder.getFromLocation(location.getLatitude(),
location.getLongitude(), 1);
tv_address.setText(addressList.get(0).getAddressLine(0));
} catch (IOException e) {
String text = "geocode didnt work";
tv_address.setText(text);
e.printStackTrace();
}
} else {
Toast.makeText(this, "the gps doesnt work", Toast.LENGTH_SHORT).show();
}
}
}
This code will retrieve my current location and update the name of the location but it will only work if I open google maps, close google maps and launch my app, it will work. Maybe this is the only way to make it work? But I wonder how other apps can track my location without opening google maps before.
yes, you can do it using its fused location provider also...without a map...
These code work without map I Hope You have apply runtime permission code
also apply for permission in the android manifest check it...
follow these URL - https://javapapers.com/android/android-location-fused-provider/
public class HomeFragment extends Fragment implements LocationListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
GoogleApiClient googleApiClient;
LocationRequest locationRequest;
Location mCurrentLocation;
private static final long INTERVAL = 1000;
private static final long FASTEST_INTERVAL = 1000;
private int Play_SERVICES_RESOLUTION_REQUEST = 11;
FragmentHomeBinding binding;
AddressListDialogBinding dialogBinding;
AddressInterface anInterface;
FirebaseFirestore firebaseFirestore;
BottomSheetDialog dialog;
public HomeFragment() {
}
protected void createLocationRequest() {
locationRequest = new LocationRequest();
locationRequest.setInterval(INTERVAL);
locationRequest.setFastestInterval(FASTEST_INTERVAL);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
LayoutInflater layoutInflater = getLayoutInflater();
binding = FragmentHomeBinding.inflate(layoutInflater);
View view = binding.getRoot();
setHasOptionsMenu(true);
return view;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
init();
}
private void init() {
if (!isGooglePlayServicesAvailable()) {
}
createLocationRequest();
anInterface = this;
// setAddress();
googleApiClient = new GoogleApiClient.Builder(getActivity())
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
#Override
public void onStart() {
super.onStart();
googleApiClient.connect();
}
#Override
public void onStop() {
super.onStop();
googleApiClient.disconnect();
}
private boolean isGooglePlayServicesAvailable() {
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity());
if (ConnectionResult.SUCCESS == status) {
return true;
} else {
GooglePlayServicesUtil.getErrorDialog(status, getActivity(), 0).show();
return false;
}
}
#Override
public void onConnected(#Nullable Bundle bundle) {
startLocationUpdates();
}
protected void startLocationUpdates() {
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
PendingResult<Status> pendingResult = LocationServices.FusedLocationApi.requestLocationUpdates(
googleApiClient, locationRequest, this);
Log.d("LocationUpdate", "Location update started ..............: ");
}
#Override
public void onConnectionSuspended(#NonNull int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onLocationChanged(Location location) {
mCurrentLocation = location;
updateUI();
}
private void updateUI() {
if (mCurrentLocation != null) {
Log.e("getLocation", "updateUI: " + mCurrentLocation.getLatitude() + ":" + mCurrentLocation.getLongitude());
Geocoder geocoder = new Geocoder(getActivity(), Locale.getDefault());
try {
List<Address> addresses = geocoder.getFromLocation(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude(), 1);
String address = addresses.get(0).getAddressLine(0);
binding.tvCurrentLocation.setText(address);
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
public void onPause() {
super.onPause();
stopLocationUpdate();
}
protected void stopLocationUpdate() {
try {
LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this);
} catch (Exception e) {
Log.e("error", "stopLocationUpdate: " + e.toString());
}
}
#Override
public void onResume() {
super.onResume();
if (googleApiClient.isConnected()) {
startLocationUpdates();
}
}
}

How to get users location using a class in android getting null pointer exception

I am using a separate class to get user's location. How to get user's location by calling interface in my activity.I cant understand How can i get user's location' latitude and longitude in my activity? It is giving me null pointer exception when i create object of class and call method
My Activity
public class missingPerson extends AppCompatActivity implements OnLocationUpdateListener {
OnLocationUpdateListener lu;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_missing_person);
final LocationHandler locationHandler = new LocationHandler(missingPerson.this,lu);
locationHandler.getDeviceLocation();
}
#Override
public void onLocationChanged(Location location) {
Location location1 = location;
String latitute = String.valueOf(location1.getLatitude());
Log.i("No Result", latitute);
}
#Override
public void onError(String error) {
}
}
Class for location
package com.example.fizatanveerkhan.citycops;
import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import java.util.List;
public class LocationHandler {
private Activity activity;
private FusedLocationProviderClient mFusedLocationProviderClient;
private Location mLastKnownLocation;
private LocationCallback mLocationCallback;
private LocationRequest mLocationRequest;
private OnLocationUpdateListener onLocationUpdateListener;
private boolean updateStartedInternally = false;
private boolean isconnected = false;
public LocationHandler(Activity activity, final OnLocationUpdateListener onLocationUpdateListener) {
this.activity = activity;
this.onLocationUpdateListener = onLocationUpdateListener;
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(activity);
createLocationRequest();
getDeviceLocation();
mLocationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
List<Location> locationList = locationResult.getLocations();
if (locationList.size() > 0) {
//The last location in the list is the newest
Location location = locationList.get(locationList.size() - 1);
mLastKnownLocation = location;
if (onLocationUpdateListener != null) {
onLocationUpdateListener.onLocationChanged(location);
if(updateStartedInternally){
stopLocationUpdate();
}
}
}
}
};
}
public boolean isConnected() {
return isconnected;
}
public 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 {
Task locationResult = mFusedLocationProviderClient.getLastLocation();
locationResult.addOnCompleteListener(activity, new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
isconnected = true;
if (task.isSuccessful()) {
// Set the map's camera position to the current location of the device.
mLastKnownLocation = (Location) task.getResult();
if (mLastKnownLocation == null) {
updateStartedInternally = true;
mFusedLocationProviderClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
} else if (mLastKnownLocation != null){
mFusedLocationProviderClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
// This message appears in logcat with latitute still it say that
// onLocationUpdateListener.onLocationChanged is invoked on null object
// reference
Log.e("Location", String.valueOf(mLastKnownLocation.getLatitude()));
onLocationUpdateListener.onLocationChanged(mLastKnownLocation);
}
}
else {
onLocationUpdateListener.onError("Can't get Location");
}
}
}) ;
} catch (SecurityException e) {
Log.e("Exception: %s", e.getMessage());
onLocationUpdateListener.onError(e.getMessage());
}
}
public void startLocationUpdates() {
if (ActivityCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
updateStartedInternally = false;
mFusedLocationProviderClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
}
private void stopLocationUpdate() {
mFusedLocationProviderClient.removeLocationUpdates(mLocationCallback);
}
//other new Methods but not using right now..
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(10000);//set the interval in which you want to get locations
mLocationRequest.setFastestInterval(5000);//if a location is available sooner you can get it (i.e. another app is using the location services)
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
}
And this is Interface
import android.location.Location;
public interface OnLocationUpdateListener {
void onLocationChanged(Location location);
void onError(String error)
}
Error
I/AssistStructure: Flattened final assist data: 4848 bytes, containing 1 windows, 15 views
E/Location: 37.4219983
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.fizatanveerkhan.citycops, PID: 14006
java.lang.NullPointerException: Attempt to invoke interface method 'void
com.example.fizatanveerkhan
.citycops.OnLocationUpdateListener.onLocationChanged
(android.location.Location)' on a null object reference
at com.example.fizatanveerkhan.citycops.
LocationHandler$2.onComplete(LocationHandler.java:88)
at com.google.android.gms.tasks.zzj.run(Unknown Source:4)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os
.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
I/Process: Sending signal. PID: 14006 SIG: 9
Application terminated.
final LocationHandler locationHandler = new LocationHandler(missingPerson.this,lu);
What is this "lu" that you pass as second argument during instance? I don't see it anywhere.
public LocationHandler(Activity activity, final OnLocationUpdateListener onLocationUpdateListener) {
//........
}
LocationHandler take OnLocationUpdateListener and set
this.onLocationUpdateListener = onLocationUpdateListener;
Then, you call
onLocationUpdateListener.onLocationChanged(mLastKnownLocation);
If you pass "lu" (that maybe is null), is pretty clear that object's onLocationUpdateListener is null.

Android LocationProvider will not update

I've set the setInterval to 10 seconds, and the setFastestInterval to 1 second, but the app doesn't update the address location. It's only loaded once.
I want it to be loaded more than once. Should I put the mLocationProvider in a loop?
Thanks for any help.
MainActivity:
public class MainActivity extends AppCompatActivity implements LocationProvider.LocationCallback {
private LocationProvider mLocationProvider;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Find my location
mLocationProvider = new LocationProvider(this, this);
}
public void handleNewLocation(Location location) {
double currentLatitude = location.getLatitude();
double currentLongitude = location.getLongitude();
float currentAccuracy = location.getAccuracy();
}
}
LocationProvider:
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.IntentSender;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
public class LocationProvider implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
public abstract interface LocationCallback {
public void handleNewLocation(Location location);
}
public static final String TAG = LocationProvider.class.getSimpleName();
/*
* Define a request code to send to Google Play services
* This code is returned in Activity.onActivityResult
*/
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
private LocationCallback mLocationCallback;
private Context mContext;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
public LocationProvider(Context context, LocationCallback callback) {
mGoogleApiClient = new GoogleApiClient.Builder(context)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mLocationCallback = callback;
// Create the LocationRequest object
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(10 * 1000) // 10 seconds, in milliseconds
.setFastestInterval(1 * 1000); // 1 second, in milliseconds
mContext = context;
}
public void connect() {
mGoogleApiClient.connect();
}
public void disconnect() {
if (mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
mGoogleApiClient.disconnect();
}
}
#Override
public void onConnected(Bundle bundle) {
Log.i(TAG, "Location services connected.");
if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
Toast.makeText(mContext, "Permission missing", Toast.LENGTH_LONG).show();
return;
}
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (location == null) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
else {
mLocationCallback.handleNewLocation(location);
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
/*
* Google Play services can resolve some errors it detects.
* If the error has a resolution, try sending an Intent to
* start a Google Play services activity that can resolve
* error.
*/
if (connectionResult.hasResolution() && mContext instanceof Activity) {
try {
Activity activity = (Activity)mContext;
// Start an Activity that tries to resolve the error
connectionResult.startResolutionForResult(activity, CONNECTION_FAILURE_RESOLUTION_REQUEST);
/*
* Thrown if Google Play services canceled the original
* PendingIntent
*/
} catch (IntentSender.SendIntentException e) {
// Log the error
e.printStackTrace();
}
} else {
/*
* If no resolution is available, display a dialog to the
* user with the error.
*/
Log.i(TAG, "Location services connection failed with code " + connectionResult.getErrorCode());
}
}
#Override
public void onLocationChanged(Location location) {
mLocationCallback.handleNewLocation(location);
}
}
Ive read https://developer.android.com/training/location/receive-location-updates but it didn't help me much.

Trouble with assigning getLatitude() to a variable

I'm in a process of writing a tracking map. In a method getDeviceLocation I want to assign:
prevLat=mLastKnownLocation.getLatitude();
prevLng=mLastKnownLocation.getLongitude();
but it crashes the app. I want to assign it for later us in distanceBetween() to get a distance after every location change. When closing the activity by killApp() it should sum up all the distances and give me a total. It also crashes the app so it's been commented.
Whole activity:
package com.example.micha.aplikacjatreningowa;
import android.Manifest;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.support.v4.app.DialogFragment;
import com.google.android.gms.common.ConnectionResult;
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.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import static android.location.Location.distanceBetween;
import static java.lang.Math.pow;
public class MapActivity extends AppCompatActivity implements OnMapReadyCallback, com.google.android.gms.location.LocationListener,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private static final String TAG = MapActivity.class.getSimpleName();
private GoogleMap mMap;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
private CameraPosition mCameraPosition;
private static final int DEFAULT_ZOOM = 20;
private static final int PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 1;
private boolean mLocationPermissionGranted = false;
private Location mLastKnownLocation;
private static final String KEY_CAMERA_POSITION = "camera_position";
private static final String KEY_LOCATION = "location";
private static final int UPDATE_INTERVAL = 1000;
private static final int FASTEST_INTERVAL = 500;
private static final int DISPLACEMENT = 1;
public double prevLat;
public double prevLng;
float totalDistance;
float[] distance;
float[] cBurned;
Float totalCalories;
public Button End;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Ustalanie mapy
setContentView(R.layout.activity_map);
//Budowanie klienta API do użytku w wyznaczaniu położenia
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, this)
.addConnectionCallbacks(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
createLocationRequest();
endButton();
}
//Zapisuje stan aplikacji
protected void onSaveInstanceState(Bundle outState) {
if (mMap != null) {
outState.putParcelable(KEY_CAMERA_POSITION, mMap.getCameraPosition());
outState.putParcelable(KEY_LOCATION, mLastKnownLocation);
super.onSaveInstanceState(outState);
}
}
#Override
public void onConnected(#Nullable Bundle bundle) {
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
//Gdy połączenie się nie uda
public void onConnectionFailed(#NonNull ConnectionResult result) {
Log.d(TAG, "Połączenie nieudane: ConnectionResult.getErrorCode() = " + result.getErrorCode());
}
//Gdy połączenie zostanie wstrzymane
public void onConnectionSuspended() {
Log.d(TAG, "Połączenie wstrzymane");
}
//Pobieranie lokacji użytkownika
private void getDeviceLocation() {
//Prośba o pozwolenie na zczytanie lokacji urządzenia
if (ContextCompat.checkSelfPermission(this.getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
}
//Pobranie lokacji urządzenia
if (mLocationPermissionGranted) {
mLastKnownLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if(mLastKnownLocation != null) {
prevLat=mLastKnownLocation.getLatitude();
prevLng=mLastKnownLocation.getLongitude();
}
}
moveCamera();
}
//Po otrzymaniu pozwolenia
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String permissions[], #NonNull int[] grantResults) {
mLocationPermissionGranted = false;
switch (requestCode) {
case PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
mLocationPermissionGranted = true;
}
}
}
updateLocationUI();
}
//Gdy mapa jest już gotowa
#Override
public void onMapReady(GoogleMap map) {
mMap=map;
updateLocationUI();
getDeviceLocation();
startLocationUpdates();
}
private void updateLocationUI() {
if (mMap == null) {
return;
}
if (ContextCompat.checkSelfPermission(this.getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
mLocationPermissionGranted = true;
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
}
if (mLocationPermissionGranted) {
mMap.setMyLocationEnabled(true);
} else {
mMap.setMyLocationEnabled(false);
mLastKnownLocation = null;
}
}
protected void startLocationUpdates() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
}
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
#Override
public void onLocationChanged(Location location) {
moveCamera();
float velocity = location.getSpeed();
float caloriesBurned;
String extra = getIntent().getStringExtra("EXTRA_MODE_TYPE");
switch (extra) {
case"walk": {
distanceBetween(prevLat, prevLng, location.getLatitude(), location.getLongitude(), distance);
prevLat=location.getLatitude();
prevLng=location.getLongitude();
double dbcaloriesBurned =(0.0215*pow(velocity*3600/1000, 3)-0.1765*pow(velocity*3600/1000, 2)+0.8710* + 1.4577*velocity*3600/1000);
caloriesBurned = (float)dbcaloriesBurned;
int count = 0;
cBurned[count] = caloriesBurned;
count++;
if (velocity > 2) {
killApp();
}
break;
}
case "run": {
distanceBetween(prevLat, prevLng, location.getLatitude(), location.getLongitude(), distance);
prevLat = location.getLatitude();
prevLng = location.getLongitude();
double dbcaloriesBurned = (0.0215 * pow(velocity * 3600 / 1000, 3) - 0.1765 * pow(velocity * 3600 / 1000, 2) + 0.8710 * +1.4577 * velocity * 3600 / 1000);
caloriesBurned = (float) dbcaloriesBurned;
int count = 0;
cBurned[count] = caloriesBurned;
count++;
if (velocity > 3) {
killApp();
}
break;
}
case "ride": {
distanceBetween(prevLat, prevLng, location.getLatitude(), location.getLongitude(), distance);
prevLat = location.getLatitude();
prevLng = location.getLongitude();
double dbcaloriesBurned = (0.0215 * pow(velocity * 3600 / 1000, 3) - 0.1765 * pow(velocity * 3600 / 1000, 2) + 0.8710 * +1.4577 * velocity * 3600 / 1000);
caloriesBurned = (float) dbcaloriesBurned;
int count = 0;
cBurned[count] = caloriesBurned;
count++;
if (velocity > 5) {
killApp();
}
break;
}
}
}
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(UPDATE_INTERVAL);
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setSmallestDisplacement(DISPLACEMENT);
}
public void endButton(){
End = (Button)findViewById(R.id.End);
End.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
killApp();
}
});
}
public void moveCamera() {
if (mCameraPosition != null) {
mMap.moveCamera(CameraUpdateFactory.newCameraPosition(mCameraPosition));
} else if (mLastKnownLocation != null) {
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(mLastKnownLocation.getLatitude(),
mLastKnownLocation.getLongitude()), DEFAULT_ZOOM));
}
}
public void killApp() {
stopLocationUpdates();
/*for(int i=0; i<=distance.length; i++) {
totalDistance += distance[i];
}
for(int j=0; j<cBurned.length; j++) {
totalCalories += cBurned[j];
}*/
AlertDialog.Builder builder = new AlertDialog.Builder(MapActivity.this);
builder.setMessage("Koniec treningu!\nPrzebiegłeś: " + totalDistance +" metrów.\nSpaliłeś: " + totalCalories +" kalorii.")
.setCancelable(false)
.setPositiveButton("Zakończ", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
})
.create().show();
}
protected void stopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(
mGoogleApiClient, this);
}
#Override
public void onConnectionSuspended(int i) {
}
}
Edit:
Crash log:
--------- beginning of crash
05-24 22:16:57.509 2930-2930/com.example.micha.aplikacjatreningowa E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.micha.aplikacjatreningowa, PID: 2930
java.lang.SecurityException: Client must have ACCESS_FINE_LOCATION permission to request PRIORITY_HIGH_ACCURACY locations.
at android.os.Parcel.readException(Parcel.java:1599)
at android.os.Parcel.readException(Parcel.java:1552)
at com.google.android.gms.internal.zzase$zza$zza.zza(Unknown Source)
at com.google.android.gms.internal.zzasg.zza(Unknown Source)
at com.google.android.gms.internal.zzash.zza(Unknown Source)
at com.google.android.gms.internal.zzary$1.zza(Unknown Source)
at com.google.android.gms.internal.zzary$1.zza(Unknown Source)
at com.google.android.gms.internal.zzaad$zza.zzb(Unknown Source)
at com.google.android.gms.internal.zzaaq.zze(Unknown Source)
at com.google.android.gms.internal.zzaaq.zzb(Unknown Source)
at com.google.android.gms.internal.zzaav.zzb(Unknown Source)
at com.google.android.gms.internal.zzaat.zzb(Unknown Source)
at com.google.android.gms.internal.zzary.requestLocationUpdates(Unknown Source)
at com.example.micha.aplikacjatreningowa.MapActivity.startLocationUpdates(MapActivity.java:187)
at com.example.micha.aplikacjatreningowa.MapActivity.onMapReady(MapActivity.java:156)
at com.google.android.gms.maps.SupportMapFragment$zza$1.zza(Unknown Source)
at com.google.android.gms.maps.internal.zzt$zza.onTransact(Unknown Source)
at android.os.Binder.transact(Binder.java:387)
at com.google.android.gms.maps.internal.bw.a(:com.google.android.gms.DynamiteModulesB:82)
at com.google.maps.api.android.lib6.impl.bf.run(:com.google.android.gms.DynamiteModulesB:1805)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Edit 2: App crashes because of startLocationUpdates() method
You are not handling android runtime permissions correctly, because you are requesting permission when condition
Manifest.permission.ACCESS_FINE_LOCATION == PackageManager.PERMISSION_GRANTED is true. Check your code one more time.
You should do something like this:
String permission = Manifest.permission.ACCESS_FINE_LOCATION;
if (!isPermissionGranted(permission)) {
if (isRationaleExplanationNeeded(permission)) {
//show dialog to explain why you need permission
} else {
ActivityCompat.requestPermissions(this, new String[]{permission},
PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
}
} else {
//do what ever you need to do
}
I assume that you are getting security exception because of not allowed permission.
Functions called above:
private boolean isPermissionGranted(String permission) {
int hasRequestedPermission = ContextCompat.checkSelfPermission(this, permission);
return hasRequestedPermission == PackageManager.PERMISSION_GRANTED;
}
private boolean isRationaleExplanationNeeded(String permission) {
return ActivityCompat.shouldShowRequestPermissionRationale(activity, permission);
}

Anonymous class is not abstract and does not override (Android + Retrofit)

I am trying to make a Google map show nearby places using retrofit following this tutorial.
I get this error:
Error:(158, 46) error: is not abstract and does not
override abstract method onFailure(Call,Throwable) in
Callback
Error:(159, 13) error: method does not override or implement a method
from a supertype
I tried to implement methods using the alt + enter, but it gets different from the tutorial, and it messes up the code.
Here is my main (it's the same from the tutorial)
MapsActivity.java
package example.googlemapsapp;
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
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.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import java.util.HashMap;
import example.googlemapsapp.POJO.Example;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
private GoogleMap mMap;
double latitude;
double longitude;
private int PROXIMITY_RADIUS = 10000;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
LocationRequest mLocationRequest;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkLocationPermission();
}
//show error dialog if Google Play Services not available
if (!isGooglePlayServicesAvailable()) {
Log.d("onCreate", "Google Play Services not available. Ending Test case.");
finish();
}
else {
Log.d("onCreate", "Google Play Services available. Continuing.");
}
// 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);
}
private boolean isGooglePlayServicesAvailable() {
GoogleApiAvailability googleAPI = GoogleApiAvailability.getInstance();
int result = googleAPI.isGooglePlayServicesAvailable(this);
if(result != ConnectionResult.SUCCESS) {
if(googleAPI.isUserResolvableError(result)) {
googleAPI.getErrorDialog(this, result,
0).show();
}
return false;
}
return true;
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
//Initialize Google Play Services
if (android.os.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);
}
Button btnRestaurant = (Button) findViewById(R.id.btnRestaurant);
btnRestaurant.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
build_retrofit_and_get_response("restaurant");
}
});
Button btnHospital = (Button) findViewById(R.id.btnHospital);
btnHospital.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
build_retrofit_and_get_response("hospital");
}
});
Button btnSchool = (Button) findViewById(R.id.btnSchool);
btnSchool.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
build_retrofit_and_get_response("school");
}
});
}
private void build_retrofit_and_get_response(String type) {
String url = "https://maps.googleapis.com/maps/";
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.build();
RetrofitMaps service = retrofit.create(RetrofitMaps.class);
Call<Example> call = service.getNearbyPlaces(type, latitude + "," + longitude, PROXIMITY_RADIUS);
call.enqueue(new Callback<Example>() {
#Override
public void onResponse(Response<Example> response, Retrofit retrofit) {
try {
mMap.clear();
// This loop will go through all the results and add marker on each location.
for (int i = 0; i < response.body().getResults().size(); i++) {
Double lat = response.body().getResults().get(i).getGeometry().getLocation().getLat();
Double lng = response.body().getResults().get(i).getGeometry().getLocation().getLng();
String placeName = response.body().getResults().get(i).getName();
String vicinity = response.body().getResults().get(i).getVicinity();
MarkerOptions markerOptions = new MarkerOptions();
LatLng latLng = new LatLng(lat, lng);
// Position of Marker on Map
markerOptions.position(latLng);
// Adding Title to the Marker
markerOptions.title(placeName + " : " + vicinity);
// Adding Marker to the Camera.
Marker m = mMap.addMarker(markerOptions);
// Adding colour to the marker
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
// move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
}
} catch (Exception e) {
Log.d("onResponse", "There is an error");
e.printStackTrace();
}
}
#Override
public void onFailure(Throwable t) {
Log.d("onFailure", t.toString());
}
});
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.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(this,
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) {
Log.d("onLocationChanged", "entered");
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
//Place current location marker
latitude = location.getLatitude();
longitude = location.getLongitude();
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
// Adding colour to the marker
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
// Adding Marker to the Map
mCurrLocationMarker = mMap.addMarker(markerOptions);
//move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
Log.d("onLocationChanged", String.format("latitude:%.3f longitude:%.3f", latitude, longitude));
Log.d("onLocationChanged", "Exit");
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
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)) {
// 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.
//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. Do the
// contacts-related task you need to do.
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
}
} else {
// Permission denied, Disable the functionality that depends on this permission.
Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
}
return;
}
// other 'case' lines to check for other permissions this app might request.
// You can add here other case statements according to your requirement.
}
}
}
The signature of onResponse differs from what you have.
You have:
public void onResponse( Response<Example> response, Retrofit retrofit)
It should be:
public void onResponse(Call<Example> call, Response<Example> response)
Your onFailure also needs to take a Call parameter:
public void onFailure(Call<Example> call, Throwable t)
It's possible the signatures of the methods have changed between versions of Retrofit, and that the tutorial is using an older version than you are. But I'm only speculating.
It's very easy to diagnose: Just read the error message and understand it:
It says that you are trying to sublcass the CallBack interface, so you have to override all the methods it declares. But you are not; because you have not overrided right the onFailure(Call<T> call, Throwable t) method.
See? You missed to add the call parameter in the onFailure method.
Do not trust so tightly on tutorials; use it as a basis, not as a Gospel. Maybe that tutorial is based on a prior version of Retrofit. (Or it maybe contains mistakes).

Categories