Request location in android - java

I have this code to request someones location in Android, can someone explain to me why it isnt working, After the location request it sets two EditText fields as he latitude and Longitude values
package com.datapost.location;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.widget.EditText;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
public class Main extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private GoogleApiClient mGoogleApiClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Create an instance of GoogleAPIClient.
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
onStart();
}
protected void onStart() {
mGoogleApiClient.connect();
super.onStart();
}
protected void onStop() {
mGoogleApiClient.disconnect();
super.onStop();
}
#Override
public void onConnected(Bundle bundle) {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.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.
return;
}
Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation != null) {
EditText mLatitudeText = (EditText) findViewById(R.id.lat);
EditText mLongitudeText = (EditText) findViewById(R.id.lon);
String s = String.valueOf(mLastLocation.getLatitude());
String f = String.valueOf(mLastLocation.getLongitude());
mLatitudeText.setText(s);
mLongitudeText.setText(f);
}
}
#Override
public void onConnectionSuspended(int i) {
return;
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
connectionResult.getErrorCode();
return;
}
}
I dont know why it wont work, tried everything seems like a basicjob to do however it just does not want to work, do I have to have an API key or something, do I need one just to get a persons location from their phone.
Any help appreciated with this
I can also post the error mess message I got
Error
06-13 15:54:56.311 11320-11320/com.datapost.location W/System: ClassLoader referenced unknown path: /data/app/com.datapost.location-1/lib/x86_64
06-13 15:54:56.339 11320-11320/com.datapost.location I/FirebaseInitProvider: FirebaseApp initialization unsuccessful
06-13 15:54:56.906 11320-11320/com.datapost.location W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
06-13 15:54:57.032 11320-11366/com.datapost.location D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
[ 06-13 15:54:57.041 11320:11320 D/ ]
HostConnection::get() New Host Connection established 0x7f6d81a1a480, tid 11320
[ 06-13 15:54:57.093 11320:11366 D/ ]
HostConnection::get() New Host Connection established 0x7f6d85b50840, tid 11366
06-13 15:54:57.109 11320-11366/com.datapost.location I/OpenGLRenderer: Initialized EGL, version 1.4
I changed the code to this for that If statement
#Override
public void onConnected(Bundle bundle) {
if(ContextCompat.checkSelfPermission(this,android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation != null) {
EditText mLatitudeText = (EditText) findViewById(R.id.lat);
EditText mLongitudeText = (EditText) findViewById(R.id.lon);
String s = String.valueOf(mLastLocation.getLatitude());
String f = String.valueOf(mLastLocation.getLongitude());
mLatitudeText.setText(s);
mLongitudeText.setText(f);
}
}
}

You need to enable geoLocation API from your google console and create a key and use that key in your app menifest like this :
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="YOUR_API_KEY"/>
also check for runtime permission for android M+

Related

Before asking for permissions Android application closed ? How resolve that?

The first time I install this application, and when I launch MapsActivity, I am asked for permissions, which is normal. But the problem is that the application closes in the meantime. How can I modify my code to keep the application open, and the permission pop-up just overlaps. Thank you very much for your answer.
Error code in logcat :
2020-02-02 11:17:01.340 11559-11574/? E/le.rsr_pechhlu: Unable to peek into adb socket due to error. Closing socket.: Connection reset by peer
2020-02-02 11:17:01.470 11559-11636/? E/AwareLog: AtomicFileUtils: readFileLines file not exist: android.util.AtomicFile#2f88384
2020-02-02 11:17:01.470 11559-11636/? E/AwareLog: AtomicFileUtils: readFileLines file not exist: android.util.AtomicFile#7fa676d
2020-02-02 11:17:01.471 11559-11603/? E/MemoryLeakMonitorManager: MemoryLeakMonitor.jar is not exist!
2020-02-02 11:17:10.787 11559-11559/com.example.rsr_pechhlup E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.rsr_pechhlup, PID: 11559
java.lang.RuntimeException: Unable to pause activity {com.example.rsr_pechhlup/com.example.rsr_pechhlup.MapsActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.location.LocationManager.removeUpdates(android.location.LocationListener)' on a null object reference
at android.app.ActivityThread.performPauseActivityIfNeeded(ActivityThread.java:4742)
at android.app.ActivityThread.performPauseActivity(ActivityThread.java:4691)
at android.app.ActivityThread.handlePauseActivity(ActivityThread.java:4626)
at android.app.servertransaction.PauseActivityItem.execute(PauseActivityItem.java:45)
at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:145)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:70)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2199)
at android.os.Handler.dispatchMessage(Handler.java:112)
at android.os.Looper.loop(Looper.java:216)
at android.app.ActivityThread.main(ActivityThread.java:7625)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:987)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.location.LocationManager.removeUpdates(android.location.LocationListener)' on a null object reference
at com.example.rsr_pechhlup.MapsActivity.onPause(MapsActivity.java:159)
at android.app.Activity.performPause(Activity.java:7663)
at android.app.Instrumentation.callActivityOnPause(Instrumentation.java:1536)
at android.app.ActivityThread.performPauseActivityIfNeeded(ActivityThread.java:4726)
at android.app.ActivityThread.performPauseActivity(ActivityThread.java:4691) 
at android.app.ActivityThread.handlePauseActivity(ActivityThread.java:4626) 
at android.app.servertransaction.PauseActivityItem.execute(PauseActivityItem.java:45) 
at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:145) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:70) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2199) 
at android.os.Handler.dispatchMessage(Handler.java:112) 
at android.os.Looper.loop(Looper.java:216) 
at android.app.ActivityThread.main(ActivityThread.java:7625) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:987) 
public class MapsActivity extends FragmentActivity implements LocationListener {
private GoogleMap googleMap; //google map is contained in the fragment work on it to change the position of the map and so on.
private Marker marker;
private Button buttonCallNow;
private RelativeLayout callPanelWrapper;
private static final int PERMS_CALL_ID = 1234; //permission identifier, unique identifier
private static final int REQUEST_PHONE_CALL = 4321;
private LocationManager locationManager; // Android manager service of android platform.
private SupportMapFragment mapFragment;
private Utils utils;
private PhoneCallListener phoneCallListener;
private boolean firstTime;
private String adresse;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps2);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
mapFragment= (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
}
/**
* //When the activity comes back to the foreground, I have to subscribe to the different location information providers, so I will receive the new location information and I will be able to resynchronize my mapping on this location.
*/
#Override
protected void onResume() {
super.onResume();
checkPermissions();
firstTime=true;
}
private void checkPermissions(){
//For older versions of android we check that the ACCES_FINE_LOCATION and ACCES_COARSE_LOCATION permissions are enabled.
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)!=PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this, new String[]{ Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION },PERMS_CALL_ID); //We must provide three parameters: it is the activity that requires the activation of these permissions (here it is this), then a table that specifies the set of permissions to allow. And we need a request code.
return;
}
locationManager= (LocationManager) getSystemService(LOCATION_SERVICE);//I ask android to give me that service locationManager. LOCATION SERVICE comes inheritance FragmentActivity, which inherits from Context, which contains this constant.
if(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){//If on this locationManager, a particular provider here : LocationManager.GPS_PROVIDER is allowed. If I have a GPS type sensor that is enabled, on the locationManager I will be able to subscribe to events.
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000,0,this);//This function requires the type of provider: LocationManager.GPS.it needs the frequency in milliseconds at which I want new location information(Here all the seconds).It needs to notify a person, who is going to receive this notification information, it's the MapsActivity, so this.
}
if(locationManager.isProviderEnabled(LocationManager.PASSIVE_PROVIDER)){//If on this locationManager, a particular provider here : LocationManager.PASIVE_PROVIDER is allowed. If I have a GPS type sensor that is enabled, on the locationManager I will be able to subscribe to events.
locationManager.requestLocationUpdates(LocationManager.PASSIVE_PROVIDER,1000,0,this);//This function requires the type of provider: LocationManager.GPS.it needs the frequency in milliseconds at which I want new location information(Here all the seconds).It needs to notify a person, who is going to receive this notification information, it's the MapsActivity, so this.
}
if(locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){//If on this locationManager, a particular provider here : NETWORK is allowed. If I have a GPS type sensor that is enabled, on the locationManager I will be able to subscribe to events.
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,1000,0,this);//This function requires the type of provider: LocationManager.GPS.it needs the frequency in milliseconds at which I want new location information(Here all the seconds).It needs to notify a person, who is going to receive this notification information, it's the MapsActivity, so this.
}
dispMap();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(requestCode==PERMS_CALL_ID){ //This method will be activated each time a permission request is made. And to know where I'm coming from I need the requestCode. This request is coupled with this requestCode here.
checkPermissions(); //i call again chack permission do disp again pop-up permission.
}
}
/**
* //When my application leaves the foreground, I unsubscribe from the different providers of location information so as not to consume a lot of resources.
*/
#Override
protected void onPause() {
super.onPause();
//If the locationManager has been initialized, I make one of this, one of the earphone of all suppliers
locationManager.removeUpdates(this);
}
private void dispMap(){
mapFragment.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
MapsActivity.this.googleMap=googleMap;
marker = googleMap.addMarker(new MarkerOptions().position(new LatLng(43.799345,6.725426)));
}
});
}
/**
* React each time new positioning information is calculated
* #param location
*/
#Override
public void onLocationChanged(Location location) { //This location is obtained through the provider. Of course this can be any provider, GPS_PROVIDER is more accurate than PASSIVE_PROVIDER etc..
double latitude= location.getLatitude();//I'm getting the latitude.
double longitude=location.getLongitude();// I'm getting the longitude.
Toast.makeText(this, "Location: " + latitude + "/" + longitude,Toast.LENGTH_SHORT).show();
LatLng googleLocation=new LatLng(latitude,longitude);
if(firstTime){
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(googleLocation, 16.2f));
adresse= Utils.getCompleteAddressString(latitude, longitude,this);
BitmapDescriptor subwayBitmapDescriptor = BitmapDescriptorFactory.fromResource(R.drawable.map_marker);
marker = googleMap.addMarker(new MarkerOptions().position(googleLocation).icon(subwayBitmapDescriptor).title(adresse));
googleMap.setInfoWindowAdapter(new CustomInfoWindowAdapter(this));
}
firstTime=false;
if(this.googleMap!=null){//If my map is correctly displayed
adresse = Utils.getCompleteAddressString(latitude, longitude,this);
googleMap.setInfoWindowAdapter(new CustomInfoWindowAdapter(this));
marker.setTitle(adresse);
marker.setPosition(googleLocation);
marker.showInfoWindow();
}
}
/**
* To react to every change of state
* #param provider
* #param status
* #param extras
*/
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
/**
* When a location provider is closed.
* #param provider
*/
#Override
public void onProviderEnabled(String provider) {
}
/**
* When a location provider is closed.
* #param provider
*/
#Override
public void onProviderDisabled(String provider) {
}
public void btnBackClick(View view) {
Intent myIntent = new Intent(this, HomeActivity.class);
startActivity(myIntent);
}
public void btnCallMapclicked(View view) {
callPanelWrapper.setVisibility(View.VISIBLE);
buttonCallNow.setVisibility(View.GONE);
}
public void buttonFinalCallClicked(View view) {
call();
}
public void popupClosedClicked(View view) {
callPanelWrapper.setVisibility(View.GONE);
buttonCallNow.setVisibility(View.VISIBLE);
}
}
}
I'm not able to put comment,Thus forward my answer as post.
you may should describe about your problem more but do you add ACCESS_FINE_LOCATION and
ACCESS_COARSE_LOCATION to your Manifest file?
EDIT:
just change onPause to following:
#Override
protected void onPause() {
super.onPause();
if(locationManager != null) // add this line to your code
locationManager.removeUpdates(this);
}
Cause:
When Permission dialog has been shown your activity onPause() is called, and since you not initialize location manager yet, it throws NullPointerException.
Try this code to initialize map with required run time permission.
public class MapActivity extends AppCompatActivity implements OnMapReadyCallback,
GoogleApiClient.OnConnectionFailedListener{
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onMapReady(GoogleMap googleMap) {
Toast.makeText(this, "Map is Ready", Toast.LENGTH_SHORT).show();
Log.d(TAG, "onMapReady: map is ready");
mMap = googleMap;
if (mLocationPermissionsGranted) {
getDeviceLocation();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(false);
init();
}
}
private static final String TAG = "MapActivity";
private static final String FINE_LOCATION = Manifest.permission.ACCESS_FINE_LOCATION;
private static final String COURSE_LOCATION = Manifest.permission.ACCESS_COARSE_LOCATION;
private static final int LOCATION_PERMISSION_REQUEST_CODE = 1234;
//vars
private Boolean mLocationPermissionsGranted = false;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
getLocationPermission();
}
private void initMap(){
Log.d(TAG, "initMap: initializing map");
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(MapActivity.this);
}
private void getLocationPermission(){
Log.d(TAG, "getLocationPermission: getting location permissions");
String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION};
if(ContextCompat.checkSelfPermission(this.getApplicationContext(),
FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
if(ContextCompat.checkSelfPermission(this.getApplicationContext(),
COURSE_LOCATION) == PackageManager.PERMISSION_GRANTED){
mLocationPermissionsGranted = true;
initMap();
}else{
ActivityCompat.requestPermissions(this,
permissions,
LOCATION_PERMISSION_REQUEST_CODE);
}
}else{
ActivityCompat.requestPermissions(this,
permissions,
LOCATION_PERMISSION_REQUEST_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
Log.d(TAG, "onRequestPermissionsResult: called.");
mLocationPermissionsGranted = false;
switch(requestCode){
case LOCATION_PERMISSION_REQUEST_CODE:{
if(grantResults.length > 0){
for(int i = 0; i < grantResults.length; i++){
if(grantResults[i] != PackageManager.PERMISSION_GRANTED){
mLocationPermissionsGranted = false;
Log.d(TAG, "onRequestPermissionsResult: permission failed");
return;
}
}
Log.d(TAG, "onRequestPermissionsResult: permission granted");
mLocationPermissionsGranted = true;
initMap(); // once permission granted then only initMap()
}
}
}
}
}

Attempting to retrieve location on Android Device... works on emulator but not real device

My issue: I am attempting to create an app that can be used university wide. It requires constant access to location. I followed a tutorial online and completed the code underneath. This code works perfectly for my android emulator, but does not work on my device. I get the permission request on my device, but nothing gets updated. Now, the strange thing is, if I use a mock location app on my device, this app DOES work. But only with the mock location app.
Does anyone have any suggestions on how to fix this?
(The xml file is just a single textview. Like i said, I was just testing this first)
package com.example.dylan.locationexample;
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private LocationManager locationManager;
private LocationListener locationListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationManager = (LocationManager) this.getSystemService(LOCATION_SERVICE);
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
Log.d("Location: ", location.toString());
TextView tv = findViewById(R.id.textView);
tv.setText(tv.getText() + Double.toString(location.getLatitude()) + "\t" + Double.toString(location.getLongitude()) + "\n");
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_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.
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},1);
}else{
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
if(ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
}
}
}
Please ensure you have the following in the manifest
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
And enable gps on your physical device.
If you still face the problem, check the permission settings on your mobile phone for the app. You may have denied permission to access location.
Here is my code am using:
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
com.google.android.gms.location.LocationListener mLocationListener = new com.google.android.gms.location.LocationListener() {
#Override
public void onLocationChanged(final Location location) {
listener.onLocation(location);
}
};
if(location != null) {
listener.onLocation(location);
}else{
locationListener = new android.location.LocationListener() {
#Override
public void onLocationChanged(Location location) {
listener.onLocation(location);
locationManager.removeUpdates(locationListener);
Log.d(TAG,"Location: " + String.valueOf(location.getLongitude()));
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
};
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
I'm actually experiencing the same thing and I found a solution to make it work on the physical device. Disable the WI-FI connection and it works. Idk how or why it works though. Now I just opened back the WI-Fi connection and it's working again. If the Wi-fi thing doesn't work for you try restarting the device.
You might also need to wait for a bit before it starts getting the location while moving around the house so it constantly changes.

Android studio does not check mFusedLocationProviderClient.getLastLocation().addOnSuccessListener and returns current location null

I am trying to get my updated location from my app. however my app does not check this block of code
public void onSuccess(Location location)
{} inside mFusedLocationProviderClient.getLastLocation()
.addOnSuccessListener(this, new OnSuccessListener(){} and returns me null location. Even my device location is turned on and the map shows my location. My code for accessing updated location is below:
protected void onCreate(Bundle savedInstanceState) {
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
}
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
Toast.makeText(this, "Map is ready", Toast.LENGTH_SHORT).show();
if (mLocationPermissionGranted) {
getDeviceLocation();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
return;
}
mMap.setMyLocationEnabled(true);
}
}
private void getDeviceLocation(){
try {
if(mLocationPermissionGranted) //true in my case
{
mFusedLocationProviderClient.getLastLocation()
.addOnSuccessListener(this, new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
// Got last known location. In some rare situations this can be null.
if (location != null) {
moveCamera(new LatLng(location.getLatitude(),location.getLongitude()),17);
// mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(),location.getLongitude()),12),2000,null);
}
else{
Toast.makeText(MapsActivity.this, "Unable to get current location", Toast.LENGTH_SHORT).show();
}
}
});
}
}catch (SecurityException ex){
}
}
I am getting the following exceptions in stacktrace
09-11 15:12:14.525 5864-5864/? E/Zygote: v2
09-11 15:12:14.530 5864-5864/? E/Zygote: accessInfo : 0
09-11 15:12:27.333 5864-5864/com.example.muzammil.maptestingproject E/BoostFramework: BoostFramework() : Exception_1 = java.lang.ClassNotFoundException: Didn't find class "com.qualcomm.qti.Performance" on path: DexPathList[[],nativeLibraryDirectories=[/system/lib, /vendor/lib]]
09-11 15:12:39.327 5864-5864/com.example.muzammil.maptestingproject E/art: The String#value field is not present on Android versions >= 6.0
Everything else is correct including manifest permissions and gradle dependencies. May be any body help me in solving my problem. Thanks in advance.
Fused Location Provider will give the location if at least one client is connected to it. If the client connects, it will immediately try to get a location. If your activity is the first client to connect and you call getLastLocation() that might not be enough time for the first location to come in.
getLastLocation() is suitable where a location is needed immediately or none at all can be used. If you really want to wait for a location it's best to use requestLocationUpdates() and wait for the callback rather than busy waiting in a thread.
Here is the method to get location using requestLocationUpdates()
LocationCallback locationCallback;
LocationRequest locationRequest;
FusedLocationProviderClient fusedLocationClient;
void getLocation() {
locationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(30 * 1000)
.setFastestInterval(5 * 1000);
locationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
super.onLocationResult(locationResult);
//Location received
}
};
fusedLocationClient = LocationServices.getFusedLocationProviderClient(getApplicationContext());
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
fusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, null);
}
And don't forget to remove location updated in onStop or onDestroy
fusedLocationClient?.removeLocationUpdates(locationCallback)

onLocationChanged() method is not getting called

I'm trying to find the location of my device using LocationManager; the onLocationChanged() method is not getting called no matter what i try (tried changing the location using mock location app, tried switching off and on the phone I'm trying to run the app on etc). Here's my code and the logcat:
LocationManager mlocationManager;
LocationListener mlocationListener;
long MIN_TIME = 5000;
float MIN_DISTANCE = 1000;
final int COARSE_LOCATION_REQUEST_CODE=102;
String LOCATION_PROVIDER = LocationManager.NETWORK_PROVIDER;
My onResume() method:
#Override
protected void onResume() {
super.onResume();
Log.d("ClimateControl", "onResume was called");
getWeatherForCurrentLocation();
}
My getWeatherForCurrentLocation() method:
private void getWeatherForCurrentLocation() {
mlocationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
mlocationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
Log.d("ClimateControl", "onLocationChanged() has been called");
String longitude = String.valueOf(location.getLongitude());
String latitude = String.valueOf(location.getLatitude());
Log.d("ClimateControl", "Latitude: " + latitude + "Longitude: " + longitude);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d("ClimateControl", "onStatusChanged() has been called");
}
#Override
public void onProviderEnabled(String provider) {
Log.d("ClimateControl", "onProviderEnabled() has been called");
}
#Override
public void onProviderDisabled(String provider) {
Log.d("ClimateControl", "onProviderDisabled() has been called");
}
};
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,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},COARSE_LOCATION_REQUEST_CODE);
}
mlocationManager.requestLocationUpdates(LOCATION_PROVIDER,MIN_TIME,MIN_DISTANCE,mlocationListener);
}
My onRequestPermissionsResult() method:
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(requestCode == COARSE_LOCATION_REQUEST_CODE){
if(grantResults.length>0 && grantResults[0]==PackageManager.PERMISSION_GRANTED){
Log.d("ClimateControl","Request granted");
getWeatherForCurrentLocation();
}
else{
Log.d("ClimateControl","Request denied");
}
}
}
My logcat regarding ClimateControl tag:
08-06 22:09:42.949 29359-29359/com.example.praty.climatecontrol D/ClimateControl: onResume was called
SideNote: I did try adding another requestLocationUpdates() implementation with the String provider as LocationManager.GPS_PROVIDER but there was a fatal error making my app crash
PS: My complete debug logcat:
08-07 16:59:35.229 9417-9417/? I/art: Late-enabling -Xcheck:jni
08-07 16:59:35.388 9417-9417/? W/System: ClassLoader referenced unknown path: /data/app/com.example.praty.climatecontrol-1/lib/arm64
08-07 16:59:35.449 9417-9417/com.example.praty.climatecontrol W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
08-07 16:59:35.812 9417-9417/com.example.praty.climatecontrol D/ClimateControl: onResume was called
08-07 16:59:35.861 9417-9486/com.example.praty.climatecontrol I/Adreno: QUALCOMM build : bc01238, I8e5c908169
Build Date : 12/06/16
OpenGL ES Shader Compiler Version: XE031.09.00.03
Local Branch :
Remote Branch : quic/LA.BR.1.3.6_rb1.10
Remote Branch : NONE
Reconstruct Branch : NOTHING
08-07 16:59:35.900 9417-9486/com.example.praty.climatecontrol I/OpenGLRenderer: Initialized EGL, version 1.4
08-07 16:59:35.900 9417-9486/com.example.praty.climatecontrol D/OpenGLRenderer: Swap behavior 1
08-07 16:59:36.581 9417-9417/com.example.praty.climatecontrol E/SpannableStringBuilder: SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
08-07 16:59:38.171 9417-9417/com.example.praty.climatecontrol D/ClimateControl: onResume was called
The reason why onLocationChanged is not getting called because you have not declared permission <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>.
Try adding missing permission in your manifest file and then retest. It should be working fine.
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
The issue I see where you call the requestLocationUpdates method.
Take it out from getWeatherForCurrentLocation method and Call it when you see permission granted for permissions in onRequestPermissionsResult.
Ofcourse, Make sure that you have 3 permissions mentioned in manifest of android.permission.INTERNET, android.permission.ACCESS_COARSE_LOCATION and android.permission.ACCESS_FINE_LOCATION
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[]
permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(requestCode == COARSE_LOCATION_REQUEST_CODE){
if(grantResults.length>0 && grantResults[0]==PackageManager.PERMISSION_GRANTED){
Log.d("ClimateControl","Request granted");
//here you know you have permission and then u can ask location updates, this will trigger locationListener methods on respective time you mentioned with below parameters.
mlocationManager.requestLocationUpdates(LOCATION_PROVIDER,MIN_TIME,MIN_DISTANCE,mlocationListener);
}
else{
Log.d("ClimateControl","Request denied");
}
}
}
Hope it helps.. !!

Android application exists and display an error `Unfortunately, TestGPS has stopped`

I'm new to android and when I googled my issue I couldn't find a proper solution to my problem.
I'm trying to develop a location based android app that can find user location automatically. My code compiles without any error in android studio manager, but when I click on Show Location button, my application exists and display an error Unfortunately, TestGPS has stopped
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.lsdias.testgps" >
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".GPSTracker"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
</manifest>
GPSTracker.java
package com.example.lsdias.testgps;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.provider.Settings;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class GPSTracker extends ActionBarActivity implements LocationListener
{
Button btnShowLocation;
private final Context mContext;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker()
{
mContext = null;
}
public GPSTracker(Context mContext)
{
this.mContext = mContext;
getLocation();
}
public Location getLocation()
{
try
{
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled)
{
// no network provider is enabled
}
else
{
this.canGetLocation = true;
// First get location from Network Provider
if (isNetworkEnabled)
{
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null)
{
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null)
{
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled)
{
if (location == null)
{
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null)
{
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null)
{
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
return location;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gpstracker);
btnShowLocation = (Button) findViewById(R.id.button_Location);
// show location button click event
btnShowLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(canGetLocation())
{
double latitude = getLatitude();
double longitude = getLongitude();
// \n is for new line
Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
}
else
{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
showSettingsAlert();
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_gpstracker, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
/**
* Function to get latitude
* */
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check if best network provider
* #return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog
* */
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// Setting Icon to Dialog
//alertDialog.setIcon(R.drawable.delete);
// On pressing Settings button
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
* */
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(GPSTracker.this);
}
}
}
logcat
09-02 12:47:51.902 1935-1935/com.example.lsdias.testgps I/art﹕ Not late-enabling -Xcheck:jni (already on)
09-02 12:47:52.384 1935-1958/com.example.lsdias.testgps D/OpenGLRenderer﹕ Render dirty regions requested: true
09-02 12:47:52.385 1935-1935/com.example.lsdias.testgps D/﹕ HostConnection::get() New Host Connection established 0xa6c40550, tid 1935
09-02 12:47:52.418 1935-1935/com.example.lsdias.testgps D/Atlas﹕ Validating map...
09-02 12:47:52.582 1935-1949/com.example.lsdias.testgps I/art﹕ Background sticky concurrent mark sweep GC freed 4140(288KB) AllocSpace objects, 0(0B) LOS objects, 28% free, 810KB/1135KB, paused 61.733ms total 123.372ms
09-02 12:47:52.607 1935-1958/com.example.lsdias.testgps D/﹕ HostConnection::get() New Host Connection established 0xa6c406b0, tid 1958
09-02 12:47:52.675 1935-1958/com.example.lsdias.testgps I/OpenGLRenderer﹕ Initialized EGL, version 1.4
09-02 12:47:52.697 1935-1958/com.example.lsdias.testgps D/OpenGLRenderer﹕ Enabling debug mode 0
09-02 12:47:52.764 1935-1958/com.example.lsdias.testgps W/EGL_emulation﹕ eglSurfaceAttrib not implemented
09-02 12:47:52.764 1935-1958/com.example.lsdias.testgps W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xa6c1ae20, error=EGL_SUCCESS
09-02 12:47:53.478 1935-1958/com.example.lsdias.testgps W/EGL_emulation﹕ eglSurfaceAttrib not implemented
09-02 12:47:53.478 1935-1958/com.example.lsdias.testgps W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xa6c1ae20, error=EGL_SUCCESS
09-02 12:47:58.675 1935-1935/com.example.lsdias.testgps D/AndroidRuntime﹕ Shutting down VM
--------- beginning of crash
09-02 12:47:58.675 1935-1935/com.example.lsdias.testgps E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.lsdias.testgps, PID: 1935
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources$Theme android.content.Context.getTheme()' on a null object reference
at android.app.AlertDialog.resolveDialogTheme(AlertDialog.java:154)
at android.app.AlertDialog$Builder.<init>(AlertDialog.java:379)
at com.example.lsdias.testgps.GPSTracker.showSettingsAlert(GPSTracker.java:240)
at com.example.lsdias.testgps.GPSTracker$1.onClick(GPSTracker.java:155)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
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:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
What's the issue here?
The problem is that mContext in GPSTracker is null, and you are creating AlertDialog with null Context.
Also you should not override Activity's constructors.
Move your getLocation(); into onCreate() method
The variable 'mContext' is defined final and it not have been initialized.I don't think the code compiles without any error in android studio. You needn't make mContext final, and should initialize in onCreate() method. If you just want mContext final, see this:
private final Context mContext = this;

Categories