Getting Coordinates From Button Press Not Working - java

I am pretty new to Android Development, and I've tried to make a method in my Android Application, where you press the button and get coordinates (Longitude and Latitude). But the program stops working on the emulator when I press the button.
I am probably just doing something wrong here. Looking through the Callstack didn't help me. It was simply too cluttered with...a lot of useless information.
How do I fix this?
public void onLocateByGMapButtonClick() {
LocationManager mloc = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
List<String> providers = mloc.getAllProviders();
Location loc = new Location(providers.get(0));
double loTude = loc.getLongitude();
double laTude = loc.getLatitude();
String newCoords = loTude + "," + laTude;
location.setText(newCoords);
Toast.makeText(this.getBaseContext(),"Location have been updated!",5);
}

The reason you application is crashing is probably because you are receiving a null pointer exception.
You have to understand that a GPS fix is not an immediate process, it might take time and in this time you don't have a location to work on unless you use the getLaskKnownLocation method (which maybe return null as well).
So what you need to to is or use:
Location loc = lm.getLastKnownLocation(provider);
or implement a LocationListener that will fire as soon as a new location update arrives.
Tutorial: http://www.vogella.com/articles/AndroidLocationAPI/article.html

Related

Getting geographical location of captured image - Android java

I'm new to android developement and I'm supposed to use Java as the programming language. I have an app where I'm supposed to be able to capture images and the geographical location of the captured images and display these details. I am displaying the image in an imageView. I have a text file where I'm storing image links as well as the captured images. So, I basically have image links and captured images that are stored in an arraylist then to a text file.
Please feel free to ask for anything that I may have missed out in the question.
I tried using EXIFInterface method I found on a Stack Overflow response, I tried using Location provider but to no avail. Maybe where I'm placing the code is incorrect, as I said, I'm new to this. I tried watching YT videos and did some research online and I'm more confused than ever at this point. Another approach I tried using was capturing the current location of the device to an invisible textView then calling it to where the image name is being stored but this did not work either.
The EXIF method I tried:
`
try {
ExifInterface exifInterface = new ExifInterface(direct); //Direct is the filepath
Log.d("Latitude", exifInterface.getAttribute(ExifInterface.TAG_GPS_LATITUDE));
Log.d("Longitude", exifInterface.getAttribute(ExifInterface.TAG_GPS_LONGITUDE));
} catch (IOException e) {
e.printStackTrace();
}
`
Location Provider method
#SuppressLint("MissingPermission")
private void showLocation() {
locationProvider.getLastLocation().addOnSuccessListener(this,
new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
if (location != null) {
hiddenLoc.setText("Current location is: Lat:" + location.getLatitude()
+ "Lon: " + location.getLongitude());
}
}
});
}
`
EXIF location is an optional interface- most images won't have one. In fact many (most?) camera apps have stopped using it by default to protect user privacy. You can try it, but don't expect it to be there.
Your location code- lastLocation will return null unless location was already up and running (generally because another app was using it). You'd need to request location updates, rather than rely on lastLocation. Please note that this gets the location of the phone now not the location when a photo was taken. So this only works if you run it when you take the photo (the exif data gets the location where the photo was taken, if its there at all).

Using MapBox to start Navigation UI causes unexpected crash

I am attempting to implement a navigation component to my application following this MapBox guide:
https://docs.mapbox.com/help/tutorials/android-navigation-sdk/
When I attempt to call .startNavigation(...) I get an unexpected error:
2020-03-08 19:51:45.786 11394-11394/com.example.mapboxnav A/libc: Fatal signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 0x8 in tid 11394 (mple.mapboxnav), pid 11394 (mple.mapboxnav)
Since the application I'm creating features many buttons, I've implemented View.OnClickListener and am calling the Navigation interface when a user presses the navigation button (R.id.startNav). However, as soon as a user presses the button the application crashes.
The currentRoute is working and shown on the map upon calling getRoute, like the example. I have verified that currentRoute is definitely not null. I have also attempted to start navigation with different coordinates without any luck.
currentRoute contains a route from the user's current/last known location to a specified destination. For reference, the line is set/generated with the following method:
public void initLine(Double lng, Double lat) {
Location lastKnownLocation = mapboxMap.getLocationComponent().getLastKnownLocation();
Point origin = Point.fromLngLat(lastKnownLocation.getLongitude(), lastKnownLocation.getLatitude());
Point destination = Point.fromLngLat(lng, lat);
getRoute(origin, destination);
}
onClick:
public void onClick(View v) {
switch (v.getId()) {
...
case R.id.startNav:
boolean simulateRoute = true;
NavigationLauncherOptions options = NavigationLauncherOptions.builder()
.directionsRoute(currentRoute)
.shouldSimulateRoute(simulateRoute)
.build();
NavigationLauncher.startNavigation(MainActivity.this, options); // Causes Crash
}
}
I spend two and a half days over this until I discovered that the problem is that we need to set the location Engine before calling :
NavigationLauncher.startNavigation(MainActivity.this, options);
so your code should look like this and it should work:
NavigationLauncherOptions options = NavigationLauncherOptions.builder()
.directionsRoute(currentRoute)
.shouldSimulateRoute(simulateRoute)
.build();
// Just add these three lines
MapboxNavigation navigation = new MapboxNavigation(DriveActivity.this, getString(R.string. mapbox_access_token));
navigation.setLocationEngine(locationEngine); mapboxMap.getLocationComponent().setLocationComponentEnabled(true);
NavigationLauncher.startNavigation(MainActivity.this, options);
Let me know how it goes
Criss
Hmm, very strange. I still feel like there's gotta be more info buried in the logcat. Maybe well above the Fatal signal 11 line? Maybe, just maybe, it's related to Location lastKnownLocation = mapboxMap.getLocationComponent().getLastKnownLocation();. Add a null check for lastKnownLocation and put
Point origin = Point.fromLngLat(lastKnownLocation.getLongitude(), lastKnownLocation.getLatitude());
Point destination = Point.fromLngLat(lng, lat);
getRoute(origin, destination);
inside of the null check block?
Maybe you're using the wrong classes? Look at the Nav SDK's NavigationLauncher test app activity: https://github.com/mapbox/mapbox-navigation-android/blob/master/app/src/main/java/com/mapbox/services/android/navigation/testapp/activity/navigationui/NavigationLauncherActivity.java#L342-L347. It's using NavigationLauncherOptions.Builder, whereas you aren't.
https://github.com/mapbox/mapbox-navigation-android/blob/master/app/src/main/java/com/mapbox/services/android/navigation/testapp/activity/navigationui/NavigationLauncherActivity.java#L365
A SIGSEGV error is thrown when you attempt to access memory incorrectly or are accessing a piece of memory that is not allotted for your use. See What causes a SIGSEGV for more information on this.
The fact that the error occurs on the line below,
NavigationLauncher.startNavigation(MainActivity.this, options);
leads me to believe that NavigationLauncherOptions options is not being assigned correctly and is possibly NULL causing you to derefrence a null pointer.
I know this isn't a perfect answer and doesn't really provide a solution to your problem, but I hope it helps bring you closer to finding an answer.
Here are some links that may help(including documentation):
https://github.com/mapbox/mapbox-navigation-android/issues/1529
https://docs.mapbox.com/android/navigation/overview/

Get distance by road between two lat lng in android

I am creating a blood bank app in which I am showing the user, his current position and different donors available near him on a map. When the user clicks on the blood request button, I show him a list of different donors available near him. Now on the list with the names of donors, I want to show the distance of that donor from the user current location. Right now I am getting distance by line which always shows 56 KM less than the actual distance. For that I am doing this :
donarLat = profiles.getLatitude();
donarLong = profiles.getLongitude();
String distance = "";
if (currentLat != null && currentLong != null && donarLat != null && donarLong != null) {
origin = new LatLng(currentLat, currentLong);
dest = new LatLng(donarLat, donarLong);
float[] result = new float[1];
// Location.distanceBetween(currentLat, currentLong,donarLat, donarLong, result);
distance = String.valueOf(SphericalUtil.computeDistanceBetween(origin,dest));
System.out.println("d9" + profiles.getName()+ " : " + distance);
I have also got the distance using Location as you can see the commented line in code but it all gives location by line but I want to get the Location by road for which I have seen a lot of answers on StackOverflow which was answered minimum 6 years ago and also tried but sometimes it crashes app or some times it does nothing. I assume that for location by the road, I have to use google direction API but how I don't understand how to use it. I have tried that API in postman but first, it gave me an error to enable direction API after doing that it asked me to enable billing method. I am attaching the photo of Postman. And will be really thankful if someone shows me how to use API properly to get the exact distance by road.
Google API is not FREE now
Some API is free for some period but charge cost after that trial period.
And they require an API key with billing info to use trial.
In your case you have to your API key is not valid.
Create an API key with billing info form this link and be sure you can use it for a trial period. If not you may get changed.

Android Location Object Always Null

I'm simply trying to write a method that returns Latitude and Longitude. I have an activity with a button and two text fields. The java class I am using extends AppCompatActivity and implements LocationListener When the button is pressed the following method is pressed:
public void startGPS(View view)
{
// Here is the code to handle permissions - you should not need to edit this.
if ( Build.VERSION.SDK_INT >= 23 &&
ContextCompat.checkSelfPermission( this, android.Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission( this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[] { android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.ACCESS_COARSE_LOCATION }, TAKE_PHOTO_PERMISSION);
}
Location location = locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000, 0, this);
}
Later on I try to print out my location in my onLocationChanged method but it was causing the app to crash. I ran it through the debugger and found that the location was always null.
I tried to this solution but it didn't work. Other examples are calling the function in onResume but I really need this to be in startGPS method.
Also, is there a chance that the error is just with my device? I'm running it on a Nexus 7 which doesn't seem to have any problems when I run Google Maps.
If are trying to return the GPS Coordinates after pressing a button that chances are you don't already have an existing GPS location stored. You should be using requestLocationUpdates and not getLastKnownLocation.
locationManager.requestLocationUpdate(LocationManager.NETWORK_PROVIDER, 5000, 0, locationListener)
When you use requestLocationUpdate it will automatically call onLocationChanged for you so you don't need to call it in your code.
You can substitute LocationManager.NETWORK_PROVIDERfor LocationManager.GPS_PROVIDER but as long as you have a WiFi connection you should be able to get coordinates.
If you are trying to use this inside try switching GPS_PROVIDER to NETWORK_PROVIDER; this will work anywhere that the phone has service.
Because Android doesn't track location when no app is requesting it, in order to save battery. GetLastKnownLocation will almost always return null. If you want an assured non-null response, use requestLocationUpdates or requestSingleLocation. Both of those are asynchronous though, so they will call a callback when a location is found (actually figuring out a location can take from a few seconds to a minute or two, depending on the type of location provider, atmospheric conditions, line of sight issues, etc. If using GPS and inside it could actually never occur.)

Getting Longitude and Latitude from the GpsMyLocationProvider (OSMdroid)

I am programming a navigation app with OSMdroid.
How do I extract latitute and longitude from the GpsMyLocationProvider into a Geopoint, so I can center the map on it?
this.mLocationOverlay = new MyLocationNewOverlay(new GpsMyLocationProvider(this),map);
this.mLocationOverlay.enableMyLocation();
I tried this. But it just makes the app crash, as soon as I press the button for this method:
mapController.setCenter((IGeoPoint) this.mLocationOverlay);
It looks like you are casting MyLocationNewOverlay to a IGeoPoint but it doesn't implement the interface IGeoPoint, so you will be getting a ClassCastException. Make sure you pass in a valid IGeoPoint to setCenter().

Categories