(Android) Get latitude and longitude, always zero - java

I have an issue, I need to get the latitude and longitude of one specific moment like taking a picture. I get the Double values, the problem is that they're always 0. I receive no exceptions, and the coordinates are uploaded successfully to Firebase Database, but when I check them in the JSON, they are always zero (I took like 20 pictures).
This is my sections code of "location" stuffs and the uploading to Firebase Database.
My Main Activity is like this.
public class MainActivity extends AppCompatActivity implements LocationListener
Global variables related to Location
double latitude;
double longitude;
This goes inside onCreate():
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
String networkProvider = LocationManager.NETWORK_PROVIDER;
String gpsProvider = LocationManager.GPS_PROVIDER;
final Location location= new Location(networkProvider);
onLocationChanged(location);{
latitude=location.getLatitude();
longitude=location.getLongitude();
}
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
locationManager.requestLocationUpdates(gpsProvider, 5000, 10, this);
This goes in a button onClickListener(), also inside onCreate() method.
//Insert coordinates to JSON Firebase database...
Coordinates coordinates = new Coordinates();
coordinates.setLatitude(location.getLatitude());
coordinates.setLongitude(location.getLongitude());
testReference.push().setValue(coordinates);
Toast.makeText(MainActivity.this, "Coordinates uploaded!", Toast.LENGTH_LONG).show();
Also I have these methods inside MainActivity:
#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) {
}

Try this:
locationManager = (LocationManager) getApplicationContext()
.getSystemService(Context.LOCATION_SERVICE);
Criteria locationCritera = new Criteria();
String providerName = locationManager.getBestProvider(locationCritera,
true);
if(providerName!=null)
location = locationManager.getLastKnownLocation(providerName);
locationListener = new MyLocationListener();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
0, locationListener);
and Implement Your Location Listener class:
private class MyLocationListener implements LocationListener {
public void onLocationChanged(Location loc) {
if (loc != null) {
location = loc;
latitude=location.getLatitude();
longitude=location.getLongitude();
}
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
check null value for getLastKnownLocation() method..

Related

Why my Location return null for the first attempt?

While I install my app first time its always return null Location but IF any other app use location then I re- run the app then my app can get my location address. How can I update location successfully from the first run?
//here is my code
public class UserinfoActivity extends AppCompatActivity implements LocationListener {
private Button button;
private EditText editText_pin, editText_mobile, editText_address;
DatabaseReference databaseReference;
MyPreferences myPreferences;
FusedLocationProviderClient fusedLocationProviderClient;
private static final int REQUEST_CODE = 101;
Location currentLocation;
Intent intentThatCalled;
public double latitude;
public double longitude;
public LocationManager locationManager;
public Criteria criteria;
public String bestProvider;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_userinfo);
databaseReference = FirebaseDatabase.getInstance().getReference("user_responses");
myPreferences = MyPreferences.getPreferences(this);
fusedLocationProviderClient= LocationServices.getFusedLocationProviderClient(this);
intentThatCalled = getIntent();
getLocation();
//optional_check
if ( ContextCompat.checkSelfPermission( this, android.Manifest.permission.ACCESS_COARSE_LOCATION ) != PackageManager.PERMISSION_GRANTED ) {
ActivityCompat.requestPermissions( this, new String[] { android.Manifest.permission.ACCESS_COARSE_LOCATION },
REQUEST_CODE);
}
Task<Location> task=fusedLocationProviderClient.getLastLocation();
task.addOnSuccessListener(new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
if(location!=null){
currentLocation=location;
}
}
});
public static boolean isLocationEnabled(Context context) {
//...............
return true;
}
protected void getLocation() {
if (isLocationEnabled(UserinfoActivity.this)) {
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
criteria = new Criteria();
bestProvider = String.valueOf(locationManager.getBestProvider(criteria, true)).toString();
//You can still do this if you like, you might get lucky:
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.
return;
}
Location location = locationManager.getLastKnownLocation(bestProvider);
if (location != null) {
Log.e("TAG", "GPS is on");
Double latitude = location.getLatitude();
float float_latitude = latitude.floatValue();
myPreferences.setlatitude(float_latitude);
Double longitude = location.getLongitude();
float float_longitude = longitude.floatValue();
myPreferences.setlongitude(float_longitude);
/*Toast.makeText(MainActivity.this, "latitude:" + latitude + " longitude:" + longitude, Toast.LENGTH_SHORT).show();
searchNearestPlace(voice2text);*/
}
else{
//This is what you need:
locationManager.requestLocationUpdates(bestProvider, 1000, 0, this);
}
}
else
{
//prompt user to enable location....
//.................
}
}
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location) {
locationManager.removeUpdates(this);
//open the map:
latitude = location.getLatitude();
longitude = location.getLongitude();
/*Toast.makeText(MainActivity.this, "latitude:" + latitude + " longitude:" + longitude, Toast.LENGTH_SHORT).show();
searchNearestPlace(voice2text);*/
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
This link might help you
http://shaoniiuc.com/android/android-receiving-location-updates-kotlin/
I'm assuming you've already COARSE and FINE locations in your manifest
Or something like this:
Log.d("Find Location", "in find_location");
this.con = con;
String location_context = Context.LOCATION_SERVICE;
locationManager = (LocationManager) con.getSystemService(location_context);
List<String> providers = locationManager.getProviders(true);
for (String provider : providers) {
locationManager.requestLocationUpdates(provider, 1000, 0,
new LocationListener() {
public void onLocationChanged(Location location) {}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status,
Bundle extras) {}
});
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
addr = ConvertPointToLocation(latitude, longitude);
String temp_c = SendToUrl(addr);
}
}
}
Call this from any method.
Source: https://stackoverflow.com/a/9873478/13319579

Find current location

I can't find the current location, always find my last location.
I have to change what.
Please help.
My project homework for school
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gpstxt = (TextView) findViewById(R.id.txtgps);
buttonGPS = (Button) findViewById(R.id.gpsbtn);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
final Location location = locationManager.getLastKnownLocation(locationManager.NETWORK_PROVIDER);
buttonGPS.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onLocationChanged(location);
}
});
}
private void onLocationChanged(Location location) {
double longtitude = location.getLongitude();
double latitude = location.getLatitude();
gpstxt.setText("Enlem:" + latitude + "\n" + "Boylam:" + longtitude);
}
}
Not the last location output.
I want to find the current location using gps.
You should not be using locationManager.getLastKnownLocation()
Rather you should subscribe to location updates.
You can check this out for more details on the implementation.
https://developer.android.com/training/location/receive-location-updates
You seem to be using the getLastKnownLocation() method which provides you with the last known location of the user.
Instead, you should be using the requestLocationUpdates() method present in the locationManager package.
Something like this should work :
// Acquire a reference to the system Location Manager
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
makeUseOfNewLocation(location);
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
Reference : https://developer.android.com/guide/topics/location/strategies.html

Get location updates using location callbacks

I'm trying to get the user location using FusedLocationProviderClient as follows:
fusedLocationProviderClient.requestLocationUpdates(mLocationRequest, locationCallback, null);
I get location updates in this location calls
locationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
super.onLocationResult(locationResult);
for (Location location : locationResult.getLocations()) {
// list of locations
}
}
};
I read that locationResult.getLocations() retrieves a list of location objects ordered from oldest to newest,
I couldn't understand that all I want is to get the user location at the moment.
Any help regarding this?
You can use locationResult.getLastLocation() to get the most up to date location available.
From the docs: LocationResult.getLastLocation()
public Location getLastLocation ()
Returns the most recent location
available in this result, or null if no
locations are available.
You could use LocationManager instead of FusedLocationProviderClient. It could be more easier.
LocationManager manager = (LocationManager) this.getSystemService(LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
Log.d("Current location", location.toString());
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
};
//Checks permission
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;
}
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
This will give you location when user moves.

User's location not correct

I'm trying to get the user's current location for my weather application but i get the location of some "US" area. I've tried multiples tutorials but failed to get the correct current location.
It returns me:
latitude: 37.421998333333335
longitude: -122.08400000000002
The location is "Mountain View,CA,US"
The code I've used is below:
GpsTracker.java
public class GpsTracker implements LocationListener {
Context context;
public GpsTracker(Context c)
{
context = c;
}
public Location getLocation()
{
if(ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){
Toast.makeText(context,"Permission not granted",Toast.LENGTH_SHORT).show();
return null;
}
LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
boolean isGpsEnabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
if(isGpsEnabled)
{
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,this);
Location l = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
return l;
}
else{
Toast.makeText(context,"Enable GPS",Toast.LENGTH_SHORT).show();
}
return null;
}
#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) {
}
}
In my main class I'm getting the location like this:
public void getLocation()
{
gpsTracker = new GpsTracker(getApplicationContext());
Location l = gpsTracker.getLocation();
if(l != null)
{
lat = l.getLatitude();
lon = l.getLongitude();
}
Log.d("User's location","Latitude"+lat);
Log.d("User's location","Longitude"+lon);
}
The Location that you need is returned in the method onLocationChanged.
So you could assign it to a variable and then return it:
private Location lastLocation;
#Override
public void onLocationChanged(Location location) {
lastLocation = location;
}
public Location getLastLocation() {
return lastLocation;
}
Call requestLocationUpdates in the onCreate of your activity and then call getLastLocation when you need to show it.
Or you can implement a callback to notify the activity when the location changes.
You are probably getting the last known location and using that tool is probably handing back this address. Consider using a better tool or just FusedLocationProviderClient. However, I like SmartLocation library personally.
https://github.com/mrmans0n/smart-location-lib
It gives fallback providers in the event of one unavailable. There is a little learning curve to use the library, but once you implement it, it works nicely.

How to run same Android app on multiple phones?

I am not sure whether the title of the question is correct but here's my problem.
I have an application with Sign up and Log in. The users have different functionalities based on their log in. All the users are led to the MapsActivity.java once they log in. I am differentiating the users there and setting the display accordingly.
What I want is if the user is logged in as xyz#gmail.com, other users shall be able to see the location of that user. It is working but on one phone. When I log in as xyz#gmail.com, the location is stored in the sharedpreferences and is also retrieved when I log in as other user on the same phone.
But when I log in as xyz#gmail.com from another phone and log in as other user from another phone (2 phones - 2 users), the phones aren't connected to each other. The xyz#gmail.com location can't be seen on the other phone.
So what am I doing wrong? How do I run the same application on 2 phones simultaneously?
Hope you understand my problem. Below is my MapsActivity.java to further clarify my problem.
Thank you.
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private LocationManager locationManager;
private LocationListener locationListener;
private Marker mLocationMarker;
public FirebaseUser user;
public Circle circle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
user = FirebaseAuth.getInstance().getCurrentUser();
if(!user.getEmail().equalsIgnoreCase("xyz#gmail.com"))
{
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
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;
}
if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, new android.location.LocationListener() {
#Override
public void onLocationChanged(Location location) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
if(mLocationMarker != null)
{
mLocationMarker.remove();
}
if(circle != null)
{
circle.remove();
}
circle = mMap.addCircle(new CircleOptions().center(latLng).radius(15).strokeColor(Color.BLUE).fillColor(Color.BLUE));
SharedPreferences sp = getSharedPreferences("MapsActivity.java", MODE_PRIVATE);
Double la = Double.longBitsToDouble(sp.getLong("la", Double.doubleToLongBits(-1)));
Double lo = Double.longBitsToDouble(sp.getLong("lo", Double.doubleToLongBits(-1)));
mLocationMarker = mMap.addMarker(new MarkerOptions().position(new LatLng(la, lo)));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 14), 1500, null);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
});
}
else if(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new android.location.LocationListener() {
#Override
public void onLocationChanged(Location location) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
if(mLocationMarker != null)
{
mLocationMarker.remove();
}
if(circle != null)
{
circle.remove();
}
circle = mMap.addCircle(new CircleOptions().center(latLng).radius(15).strokeColor(Color.BLUE).fillColor(Color.BLUE));
SharedPreferences sp = getSharedPreferences("MapsActivity.java", MODE_PRIVATE);
Double la = Double.longBitsToDouble(sp.getLong("la", Double.doubleToLongBits(-1)));
Double lo = Double.longBitsToDouble(sp.getLong("lo", Double.doubleToLongBits(-1)));
mLocationMarker = mMap.addMarker(new MarkerOptions().position(new LatLng(la, lo)));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 14), 1500, null);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
});
}
}
else
{
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
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;
}
if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, new android.location.LocationListener() {
#Override
public void onLocationChanged(Location location) {
double lat = location.getLatitude();
double lon = location.getLongitude();
LatLng lolo = new LatLng(lat, lon);
if(mLocationMarker != null)
{
mLocationMarker.remove();
}
mLocationMarker = mMap.addMarker(new MarkerOptions().position(lolo));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(lolo, 14), 1500, null);
SharedPreferences sp = getSharedPreferences("MapsActivity.java", MODE_PRIVATE);
SharedPreferences.Editor edit = sp.edit();
edit.putLong("la", Double.doubleToLongBits(lat));
edit.putLong("lo", Double.doubleToLongBits(lon));
edit.apply();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
});
}
else if(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new android.location.LocationListener() {
#Override
public void onLocationChanged(Location location) {
double lat = location.getLatitude();
double lon = location.getLongitude();
LatLng lolo = new LatLng(lat, lon);
if(mLocationMarker != null)
{
mLocationMarker.remove();
}
mLocationMarker = mMap.addMarker(new MarkerOptions().position(lolo));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(lolo, 14), 1500, null);
SharedPreferences sp = getSharedPreferences("MapsActivity.java", MODE_PRIVATE);
SharedPreferences.Editor edit = sp.edit();
edit.putLong("la", Double.doubleToLongBits(lat));
edit.putLong("lo", Double.doubleToLongBits(lon));
edit.apply();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
});
}
}
}
/**
* 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;
}
}

Categories