I am creating an app that only checks for location when user clicks a button.
here is my code, and it returns null when i call getLastKnownLocation, even after I call requestLocationUpdates:
public void main(String[] args, int iteration, Context context){
Criteria criteria = new Criteria();
LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
LocationListener loc_listener = new LocationListener() {
public void onLocationChanged(Location l) {
}
public void onProviderEnabled(String p) {}
public void onProviderDisabled(String p) {}
public void onStatusChanged(String p, int status, Bundle extras) {}
};
String bestProvider = locationManager.getBestProvider(criteria, false);
locationManager.requestLocationUpdates(bestProvider, 0, 0, loc_listener);
Location location = locationManager.getLastKnownLocation(bestProvider);
location = locationManager.getLastKnownLocation(bestProvider);
double lat;
double lon;
try {
lat = location.getLatitude();
lon = location.getLongitude();
} catch (NullPointerException e) {
lat = -1.0;
lon = -1.0;
}
Log.i("results:", String.valueOf(lat) + " " + String.valueOf(lon) + " 10NN");}}
the location service on the device is enabled.
Thanks very much!
getLastKnownLocation will return null until the callback onLocationChanged() is triggered. This may take several minutes for GPS, even if the sky is clearly visible. If you are indoors it may never run. You have to wait for it to run.
try this pls
mGoogleMap.setOnMyLocationButtonClickListener(new OnMyLocationButtonClickListener() {
#Override
public boolean onMyLocationButtonClick()
{
Location myLocation = mGoogleMap.getMyLocation();
onLocationChanged(myLocation);
return false;
}
});
Related
I have got a small problem, my GPS Tracker keeps asking for activating Location while i activate it. I analysed and reanalysed my class but can't find my error...
Someboy care to help?
GPSTracker.java
public class GPSTracker extends Service implements LocationListener {
private final Context context;
Location location;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
double latitude;
double longitude;
private static final long MinDistanceChangeUpdate = 10;
private static final long MinTimeUpdate = 1000 * 60 * 1;
protected LocationManager locationManager;
public GPSTracker(Context context){
this.context = context;
getLocation();
}
public Location getLocation(){
try{
locationManager = (LocationManager)getSystemService(LOCATION_SERVICE);
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if(!isNetworkEnabled && !isGPSEnabled){
}else{
this.canGetLocation = true;
if(isNetworkEnabled){
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MinTimeUpdate, MinDistanceChangeUpdate, this);
if(locationManager != null){
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if(location != null){
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
if(isGPSEnabled){
if(location == null){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MinTimeUpdate, MinDistanceChangeUpdate, this);
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;
}
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(GPSTracker.this);
}
}
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
return latitude;
}
public double getLongitude (){
if(location != null){
longitude = location.getLongitude();
}
return longitude;
}
public boolean canGetLocation(){
return this.canGetLocation;
}
public void showSettingsAlert(){
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setTitle("GPS is Settings! ");
alertDialog.setMessage("GPS is not enable, Wanna enable?");
alertDialog.setPositiveButton("Ok", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
context.startActivity(intent);
}
});
alertDialog.setNegativeButton("No", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
#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) {
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
MainActivity.java
public class MainActivity extends Activity {
Button btnshowLocation;
GPSTracker gps;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnshowLocation = (Button)findViewById(R.id.showLocation);
btnshowLocation.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
gps = new GPSTracker(MainActivity.this);
if(gps.canGetLocation()){
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
Toast.makeText(getApplicationContext(), "Latitude = " + latitude + " Longitude = " + longitude, Toast.LENGTH_LONG).show();
} else {
gps.showSettingsAlert();
}
}
});
}
}
Stracktrace
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.content.Context.getSystemService(java.lang.String)' on a null object reference
04-26 23:55:51.943 21374-21374/com.example.dell.exampleapplication W/System.err﹕ at android.content.ContextWrapper.getSystemService(ContextWrapper.java:582)
04-26 23:55:51.943 21374-21374/com.example.dell.exampleapplication W/System.err﹕ at com.example.dell.exampleapplication.GPSTracker.getLocation(GPSTracker.java:44)
04-26 23:55:51.943 21374-21374/com.example.dell.exampleapplication W/System.err﹕ at com.example.dell.exampleapplication.GPSTracker.<init>(GPSTracker.java:39)
04-26 23:55:51.943 21374-21374/com.example.dell.exampleapplication W/System.err﹕ at com.example.dell.exampleapplication.MainActivity$1.onClick(MainActivity.java:28)
Edit : Added Stracktrace
Thanks in advance,
Funny to see a snippet of some code I posted a long time ago in an SO answer :-D Location servise GPS Force closed
Many things has happened since then and my recommendation these days is to use https://github.com/mcharmas/Android-ReactiveLocation
Mainly because:
It uses the Fused location (more battery efficient + better accuracy)
Way less boilerplate code
Additional power of RxJava (no need to dive into details about RxJava for simple usage but it has some awesome features)
I added Activity Recognition to the library (so I like to advertise how awesome I think it is)
To get most recent location the only code you need to write is:
ReactiveLocationProvider locationProvider = new ReactiveLocationProvider(context);
locationProvider.getLastKnownLocation()
.subscribe(new Action1<Location>() {
#Override
public void call(Location location) {
doSthImportantWithObtainedLocation(location);
}
});
To vaguely answer your question, my suspicion is that perhaps you have GPS turned on but not WiFi location (just guessing though).
If you are determined to use the code you posted, then I would suggest adding various Log outputs to debug the situation. Something like:
public Location getLocation(){
try{
locationManager = (LocationManager)getSystemService(LOCATION_SERVICE);
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if(!isNetworkEnabled && !isGPSEnabled){
Log.e("GPSTracker", "!isNetworkEnabled && !isGPSEnabled");
Log.e("GPSTracker", "is network location enabled: " + isNetworkEnabled );
Log.e("GPSTracker", "is GPS location enabled: " + isGPSEnabled);
}else{
this.canGetLocation = true;
if(isNetworkEnabled){
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MinTimeUpdate, MinDistanceChangeUpdate, this);
if(locationManager != null){
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if(location != null){
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
if(isGPSEnabled){
if(location == null){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MinTimeUpdate, MinDistanceChangeUpdate, this);
if(locationManager != null){
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location != null){
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
}catch(Exception e){
Log.e("GPSTracker", "error getting location", e);
e.printStackTrace();
}
return location;
}
Otherwise pose less restrictive constraints on the canGetLocation boolean (as it is really that variable that is causing you problems)
Changing:
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if(!isNetworkEnabled && !isGPSEnabled){
}else{
this.canGetLocation = true;
...
To
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
this.canGetLocation = isNetworkEnabled || isGPSEnabled;
if(!isNetworkEnabled && !isGPSEnabled){
}else{
...
I have two classes "GPSTracker" and "Live".
The GPSTracker has the GPS related functions i.e. to get the latitude and the longitude, while the Live class calls it to get the current Latitude and the Longitude and then calculate the distance travelled.
My problem is that I am not getting any changes in the location, the location remains at whatever it is at the start! No locationUpdates!
GPSTracker.java:
public class GPSTracker extends Service implements LocationListener
{
private final Context mContext;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
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 =5; // 5 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 5; // 5 seconds
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context)
{
this.mContext = context;
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;
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;
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
* */
public void stopUsingGPS()
{
if(locationManager != null)
{
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* 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 GPS/wifi enabled
* #return boolean
* */
public boolean canGetLocation()
{
return this.canGetLocation;
}
/**
* Function to show settings alert dialog
* On pressing Settings button will lauch Settings Options
* */
public void showSettingsAlert()
{
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS is not enabled");
// Setting Dialog Message
alertDialog.setMessage("Enable location services to determine your location.");
// 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();
}
#Override
public void onLocationChanged(Location location)
{
}
#Override
public void onProviderDisabled(String provider)
{
}
#Override
public void onProviderEnabled(String provider)
{
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
#Override
public IBinder onBind(Intent arg0)
{
return null;
}
}
Live.java:
public class Live extends Activity implements LocationListener
{
GPSTracker gps;
Location newLocation = new Location(LocationManager.GPS_PROVIDER);
Location oldLocation = new Location(LocationManager.GPS_PROVIDER);
float distanceTravelled=0;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_live);
startactivity();
}
public void startactivity()
{
gps = new GPSTracker(Live.this);
if(gps.canGetLocation())
{
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
Toast.makeText(getApplicationContext(), "Your Location is: \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
newLocation.setLatitude(latitude);
newLocation.setLongitude(longitude);
}
else
{
gps.showSettingsAlert();
}
}
public void resumeactivity()
{
gps = new GPSTracker(Live.this);
if(gps.canGetLocation())
{
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
//Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
newLocation.setLatitude(latitude);
newLocation.setLongitude(longitude);
}
else
{
}
}
public void onResume()
{
super.onResume();
resumeactivity();
}
#Override
public void onLocationChanged(Location location)
{
oldLocation.set(newLocation);
newLocation.set(location);
//resumeactivity();
distanceTravelled+=newLocation.distanceTo(oldLocation);
String stringDistance= Float.toString(distanceTravelled);
TextView distance = (TextView) findViewById(R.id.textDistance);
distance.setText(stringDistance);
}
#Override
public void onProviderDisabled(String arg0)
{
GPSTracker gps = new GPSTracker(Live.this);
gps.showSettingsAlert();
}
#Override
public void onProviderEnabled(String arg0)
{
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2)
{
}
I was facing same problem with my app, so what I did is reboot phone and Start the app under clear sky. It will might help you.
You can find a working example here. It is not calculating the distance, but this should be easy to add.
My code is supposed to find out the users location and place a marker on the map upon entering the application. My location value always equals null, and never receives a value.
if (location != null) {
lat = (int) (location.getLatitude() * 1E6);
longi = (int) (location.getLongitude() * 1E6);
GeoPoint ourLocation = new GeoPoint(lat, longi);
OverlayItem overlayItem = new OverlayItem(ourLocation, "AYO",
"Whats good yo");
CustomPinpoint custom = new CustomPinpoint(d, CampusMap.this);
custom.insertPinpoint(overlayItem);
overlayList.add(custom);
} else {
Toast.makeText(CampusMap.this, "Couldn't get provider",
Toast.LENGTH_SHORT).show();
}
}
I've had a relatively similar issue with a GPS RPG I was working on and here are some things I noticed:
Firstly, it can take a while for your location to initially be found, which would cause that issue since you're only checking if the location is null.
You may also want to make sure the device's location services are actually enabled before doing anything:
private boolean doLocationsCheck(){
if(!checkLocationEnabled()){
final CharSequence[] items = {"Yes", "No"};
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setCancelable(false);
builder.setTitle("Location must be enabled to play this game! Would you like to enable it now?");
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
final int i = item;
runOnUiThread(new Runnable() {
public void run() {
if(i == 0){
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
quit();
}
else{
quit();
}
}
});
}
}).show();
AlertDialog alert = builder.create();
return false;
}
else {
return true;
}
}
private boolean checkLocationEnabled(){
LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean enabled = service.isProviderEnabled(LocationManager.GPS_PROVIDER) || service.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
return enabled;
}
After I've made sure the providers are available I setup a connection like so:
private void setupLocation() {
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(final Location location) {
runOnUiThread(new Runnable() {
public void run() {
mLocation = location;
//Log.d(TAG, "Latitude: " + location.getLatitude() + " - Longitude: " + location.getLongitude());
saveLocation();
}
});
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
//Can set to GPS or network, whichever is available
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
The location is then set in a global variable whenever it's updated, and then saved to the preferences. This way, in the event that the providers are enabled, but are taking a while to retrieve the location, the user can still continue to use the application with their last known location that the app stored (does not apply to the first time the program is run).
I know I left out a lot there, but I figured it wasn't really necessary since it was either self-explanatory or already explained in a previous answer.
Cheers~
/*
* getting the best location using the location manager
* Constants.MINIMUM_TIME_BETWEEN_UPDATES = 1000 Constants.MINIMUM_TIME_BETWEEN_UPDATES = 1
*/
LocationManager mLocation;
private String mBestProvider;
// in your onCreate() do the following
mLocation = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
mBestProvider = mLocation.getBestProvider(criteria, false);
Location location = mLocation.getLastKnownLocation(mBestProvider);
mLocation.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
Constants.MINIMUM_TIME_BETWEEN_UPDATES,
Constants.MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
new LocationListenerManager()
);
// and use the following locationListener inner class
private class LocationListenerManager implements LocationListener {
public void onLocationChanged(Location location) {
String message = String.format(
"New Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude()
);
latitude = location.getLatitude();
longitude = location.getLongitude();
Toast.makeText(MapViewActivity.this, message, Toast.LENGTH_LONG).show();
Log.v("poiint=====", ""+message);
}
public void onStatusChanged(String s, int i, Bundle b) {
Toast.makeText(MapViewActivity.this, "Provider status changed",
Toast.LENGTH_LONG).show();
}
public void onProviderDisabled(String s) {
Toast.makeText(MapViewActivity.this,
"Provider disabled by the user. GPS turned off",
Toast.LENGTH_LONG).show();
}
public void onProviderEnabled(String s) {
Toast.makeText(MapViewActivity.this,
"Provider enabled by the user. GPS turned on",
Toast.LENGTH_LONG).show();
}
}
You have to initialize the locationlistener in the onstartActivity before on create so that it location obtain the location value before onCreate.
My code putput always goes in else part. IT means {location} is null.
Any suggestions?
locManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0, locationListener);
location = locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location != null)
{
double latitude = location.getLatitude();
double longitude = location.getLongitude();
} else {
//
}
.....
.....
....
If locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER) returns null then it means you have never been located.
If you want to get the new location, you should make you activity extend the LocationListener interface and implement the following.
public void onLocationChanged(Location location) {
// Code to execute after being located
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
Don't forget to remove the location updates afterwards.
I post a question not long ago. Basically what I am trying to do is have my location manager return my longitude and latitude. My getBestProvider() method returns network, however my locationManager.getLastKnownLocation(provider) returns null. As you can see I've implemented the listener. I must have done something wrong.
Here is the code.
public class Activity1 extends Activity implements LocationListener {
private LocationManager locationManager;
private String provider;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
readFile();
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
System.out.println(provider);
System.out.println(locationManager.getProviders(criteria, false));
System.out.println(locationManager.getProvider("network"));
System.out.println(locationManager.getAllProviders());
Location location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
int lat = (int) (location.getLatitude());
int lng = (int) (location.getLongitude());
System.out.println(String.valueOf(lat));
System.out.println(String.valueOf(lng));
} else {
System.out.println("Provider not available");
System.out.println("Provider not available");
}
}#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
/* Remove the locationlistener updates when Activity is paused */
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location) {
int lat = (int) (location.getLatitude());
int lng = (int) (location.getLongitude());
System.out.println(String.valueOf(lat));
System.out.println(String.valueOf(lng));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Disenabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
}
LocationManager locationManager;
String context = Context.LOCATION_SERVICE;
locationManager = (LocationManager)getSystemService(context);
String provider = LocationManager.NETWORK_PROVIDER;
Location location = locationManager.getLastKnownLocation(provider);
updateWithNewLocation(location);
}
private void updateWithNewLocation(Location location){
String latLongString;TextView myLocationText;
myLocationText = (TextView)findViewById(R.id.myLocationText);
if (location != null) {
double lat = location.getLatitude();
double lng = location.getLongitude();
latLongString = "Lat:" + lat + "\nLong:" + lng;
} else { latLongString = "No location found"; }
}