Android: How to initialize a variable of type "Location" (other than making it equal to null)

AndroidGeolocation

Android Problem Overview


I'm looking to test some code I've written and to do so I need to construct a variable of type Location and to give it a long / lat value but I'm unsure how I would do so. Any ideas?

Android Solutions


Solution 1 - Android

The API documentation is quite clear on this. First create a new Location instance:

Location loc = new Location("dummyprovider");

And then use the setter methods to set the location parameters you need, e.g.:

loc.setLatitude(20.3);
loc.setLongitude(52.6);

Solution 2 - Android

Location object = new Location("service Provider");

it will create an object of Type Location that contains the initial Latitude and Longitude at location '0' to get the initial values use

double lat = object.getLatitude();
double lng = object.getLongitude();

Solution 3 - Android

In Kotlin using LocationManager class you can pass the required location provider like:

val location = Location(LocationManager.NETWORK_PROVIDER) // OR GPS_PROVIDER based on the requirement
location.latitude = 42.125
location.longitude = 55.123

Solution 4 - Android

You can write a method:

Location createNewLocation(double longitude, double latitude) {
    Location location = new Location("dummyprovider");
    location.setLongitude(longitude);
    location.setLatitude(latitude);
    return location;
}

And then call it:

Location myLoc = createNewLocation(dLong, dLati);

Or you can use string with Double.parse():

Location myLoc = createNewLocation(Double.parse("s.Long"), Double.parse("s.Lati"));

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSkizitView Question on Stackoverflow
Solution 1 - AndroidMatti VirkkunenView Answer on Stackoverflow
Solution 2 - AndroidAtta UllahView Answer on Stackoverflow
Solution 3 - AndroidShailendra MaddaView Answer on Stackoverflow
Solution 4 - AndroidKuvalyaView Answer on Stackoverflow