I am trying to find out the latitude and longitude in an Android application. The code that I am using is as follows:-
protected int findZipCode() {
LocationManager lm = (LocationManager) getApplicationContext()
.getSystemService(Context.LOCATION_SERVICE);
LocationListener listener = new MyLocationListener();
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 60000,
1000, listener);
if (zipCode == null) {
return 0;
} else {
return Integer.parseInt(zipCode);
}
}
private class MyLocationListener implements LocationListener {
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
if (location != null) {
Geocoder geo = new Geocoder(getApplicationContext());
List<Address> addr = null;
try {
addr = geo.getFromLocation(location.getLatitude(),
location.getLatitude(), 5);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
zipCode = addr.get(0).getPostalCode();
}
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
But this code seems to always return a null value for the zipcode. Any help would be great.
Thanks in advance!!
As your MyLocationListener is running in parallel at that point your zipCode is null therefore you are getting 0 value.
Fix
You can wait the MyLocationListener to complete and pass a interface method to this listener and on the complete of this function you can call that method.
What are you doing dude?
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 60000,1000, listener);
The above line is a asynchronus call, listener will be called when you get a position fix.
You can't check for zipcode right after this line.
In listner when you get the value of zipcode, implement some interface/callback which will give you the value of zipcode in your activity or where ever you want.
Related
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_NEW_OUTGOING_CALL)) {
String phonenum = intent.getExtras().getString(Intent.EXTRA_PHONE_NUMBER);
if (phonenum.equals("111")) {
locationmanager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
locationmanager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationlistener);
Toast.makeText(context, "The Gps values are..." + lon, Toast.LENGTH_LONG).show();
}
}
}
private static LocationListener locationlistener = new LocationListener() {
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
lat = Double.toString(location.getLatitude());
lon = Double.toString(location.getLongitude());
}
};
hi,
when i dial 111 on my dial pad my app which is pre installed on my device should toast the latitude and logitude values.I tried a sample app which displays toast message on dial of 111 making use of broadcast receiver.Above is the code which i tried.Can any help me how to get the latitude and logitude values from this fucntion.
private Location getLastBestLocation() {
Location locationGPS = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Location locationNet = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
long GPSLocationTime = 0;
if (null != locationGPS) { GPSLocationTime = locationGPS.getTime(); }
long NetLocationTime = 0;
if (null != locationNet) {
NetLocationTime = locationNet.getTime();
}
if ( 0 < GPSLocationTime - NetLocationTime ) {
return locationGPS;
}
else {
return locationNet;
}}
I am trying to get user's city from EditText and then check if it is valid or not. If there is a little typo, then I want to correct it on the EditText and then show it back to user.
I have been searching for this for quite some time but what I am getting is to get user current location and then get its location according to lat and long values. But I don't want to do this.
Here's what I am doing right now, but I don't want to do it this way
userDataFrag.loc.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 0, 0, new LocationListener() {
#Override
public void onStatusChanged(String provider,
int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
userLat = location.getLatitude();
userLong = location.getLongitude();
Geocoder geocoder = new Geocoder(getActivity(),
Locale.getDefault());
List<Address> addresses;
try {
addresses = geocoder.getFromLocation(userLat,
userLong, 1);
CityName = addresses.get(0).getAddressLine(0);
StateName = addresses.get(0).getAddressLine(1);
CountryName = addresses.get(0).getAddressLine(2);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Can any one suggests me a better way to do it?
of course my question be duplicate. but i can not found good answer for my solution.
i want to write a custom general class that can found current location by location manager and own detect gps enabled or network enabled or use cached and stored locations when device has not gps or network enable. and above all stop work after found first location any way. but i did these works for it : 1- create two locationlistener classes(GPSListener and networkListner):
public class GPSListener implements LocationListener {
LocationManager locationManager=null;
public Boolean found=false;
public Location mainLocation=null;
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
found=true;
mainLocation= location;
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
public class NetworkListener implements LocationListener {
LocationManager locationManager=null;
public Boolean found=false;
public Location mainLocation=null;
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
found=true;
mainLocation=location;
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
then i use these classes in my activity same this:
LatLng result = null;
final LocationManager locationManager = (LocationManager) this
.getSystemService(Context.LOCATION_SERVICE);
if (DeviceHelper.IsGPSEnabled()) {
GPSListener gpsListener = new GPSListener();
// if(gpsListener.found)
// {
if (gpsListener.mainLocation != null) {
ToastHelper.Show(this,
"GPS : " + gpsListener.mainLocation.toString());
gpsListener = null;
result = new LatLng(gpsListener.mainLocation.getLatitude(),
gpsListener.mainLocation.getLongitude());
}
// }
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 0, 0, gpsListener);
}
else if (DeviceHelper.HasConnect()) {
NetworkListener netListener = new NetworkListener();
// if(netListener.found)
// {
if (netListener.mainLocation != null) {
ToastHelper.Show(this,
"NETWORK : " + netListener.mainLocation.toString());
netListener = null;
result = new LatLng(netListener.mainLocation.getLatitude(),
netListener.mainLocation.getLongitude());
}
// }
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0, netListener);
} else {
;
Location loc = LocationHelper.getLastKnownLoaction(false);
if (loc != null) {
ToastHelper.Show(this, "LAST : " + loc.toString());
result = new LatLng(loc.getLatitude(), loc.getLongitude());
}
}
if (result != null) {
LogHelper.Add("LL", String.valueOf(result.latitude));
LocationHelper.MyLatLng = result;
StaticObjects.mainMap.addMarker(new MarkerOptions().position(result));
MapHelper.CameraGo( result, 15);
} else {
LogHelper.Add("ERR:", "NULL");
}
i know this not work because manager can not found as a good time before place that i show found location. totally i want to write a general class for finding current location that can stop when found first location.
First, you don't need 2 classes for listening GPS-Glonass and Network updates. You can use just one object as a listener to both providers--since provider can be easily obtained from Location object:
if(location.getProvider().equals(LocationManager.GPS_PROVIDER)){
// it is GPS
} else if (location.getProvider().equals(LocationManager.NETWORK_PROVIDER)){
// it is Network
}
Second, to know status of provider(s) you should implement LocationListener's onStatusChanged() callback. If a provider is unavailable at the moment you subscribe LocationListener, this callback is invoked immediately:
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
if (provider.equals(LocationManager.GPS_PROVIDER)
&& (status == LocationProvider.OUT_OF_SERVICE || status == LocationProvider.TEMPORARILY_UNAVAILABLE)){
// gps is unavailable
} else if (provider.equals(LocationManager.NETWORK_PROVIDER)
&& (status == LocationProvider.OUT_OF_SERVICE || status == LocationProvider.TEMPORARILY_UNAVAILABLE)){
// network provider is unavailable
}
}
Third, to unsubscribe your object from location updates, use:
locationManager.removeUpdates(locationListener);
this will stop obtaining location updates and shut down GPS-Glonass location service if no other apps need it.
I'm trying to make a weather app that uses Geocoder to get the current city, and then uses AsyncTask to get weather data from an api and then parse it. But when I input the current city into the AsyncTask execute() method, my app crashes:
private double latitude;
private double longitude;
String address;
LocationManager lm;
LocationListener ll;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
address = getAddress(latitude, longitude); // getAddress() is below
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
ll = new myLocationListener();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll);
}
private class myLocationListener implements LocationListener {
#Override
public void onLocationChanged(android.location.Location location) {
latitude = location.getLatitude();
longitude = location.getLongitude();
String address = getAddress(latitude, longitude);
Task task = new Task(); // Task extends AsyncTask
task.execute(new String[] { address });
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
public String getAddress(double lat, double lon) {
Geocoder geocoder = new Geocoder(this, Locale.ENGLISH);
String ret = "";
try {
List<Address> addresses = geocoder.getFromLocation(
lat, lon, 10);
if (addresses != null) {
Address returnedAddress = addresses.get(0);
StringBuffer str = new StringBuffer();
str.append(returnedAddress.getLocality());
str.append(",");
str.append(returnedAddress.getCountryName());
ret = str.toString();
} else {
ret = "No Address returned!";
}
} catch (IOException e) { // TODO Auto-generated catch block
e.printStackTrace();
ret = "Can't get Address!";
}
return ret;
}
I know for a fact that my getAddress() method works like it's supposed to. When I hardcode a city and state into the address field, it works like a charm. However, when I call my getAddress() method and set it to address, and then input it into execute(), the app crashes and it says that getFromLocation() returned null. Why is this happening? Is it the order of my code? Thank you for all answers in advance.
Make sure your GPS is enabled and you are not testing from the emulator. The provider will return null if it is not enabled as per the documentation. Since you need the current location and probably you do not want updates I will recommend you use requestSingleUpdate(). A better option will be to use the new LocationClient Class that is part of Google Services; its fused provider gets the best Location available for you.
i am developing location based project where i am using the following code
i am using google api 8 for the project
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
currloc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
TextView t = (TextView)findViewById(R.id.textView1);
try{
t.setText("Your current location is - "+currloc.getLatitude()+","+currloc.getLongitude());
}catch (Exception e) {
// TODO: handle exception
t.setText("cant find current location ");
}
this code works fine on my galaxy tab even on htc
but when i use nexus it returns null value for location.
do i need to change my api level or is there any specific requirement for galaxy nexus
thank you in advance :)
Please follow the line of code..
Step1: into your oncreate
LocationListener locationListener = new LocalLocationListener();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
Step2: into class body
/**Listener on location change*/
private class LocalLocationListener implements LocationListener
{
public void onLocationChanged(Location location)
{
String text = "My current Location is: "+location.getLatitude()+", "+location.getLongitude();
GeoPoint geoPoint = new GeoPoint((int)(location.getLatitude()* 1E6), (int)(location.getLatitude() * 1E6));
mapController_.animateTo(geoPoint);
Toast.makeText(LocalMap.this, text, Toast.LENGTH_SHORT).show();
Log.i("onLocationChanged", text);
}
public void onProviderDisabled(String provider)
{
// TODO Auto-generated method stub
Toast.makeText(LocalMap.this, "GPS Disable", Toast.LENGTH_SHORT).show();
Log.i("onProviderDisabled", "GPS Disable");
}
public void onProviderEnabled(String provider)
{
// TODO Auto-generated method stub
Toast.makeText(LocalMap.this, "GPS Enable", Toast.LENGTH_SHORT).show();
Log.i("onProviderEnabled", "GPS Enable");
}
public void onStatusChanged(String provider, int status, Bundle extras)
{
// TODO Auto-generated method stub
}