Logging location address to LogCat - android

A part of my app is attempting to update the location (using DDMS with an emulator in Eclipse) and then get the address to print to LogCat.
My code:
LocationManager locationManager;
String providerName = LocationManager.GPS_PROVIDER;
LocationProvider gpsProvider;
public void enable()
{
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); //Need to ask for this system service
Criteria criteria = new Criteria(); //Setting the criteria for the location provider
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setPowerRequirement(Criteria.POWER_HIGH);
criteria.setAltitudeRequired(true);
criteria.setBearingRequired(true);
criteria.setSpeedRequired(true);
criteria.setCostAllowed(true);
String provider = LocationManager.GPS_PROVIDER;
int time = 5000; //Time in ms
int distance = 5; //Distance in meters
LocationListener myLocationListener = new LocationListener()
{
public void onLocationChanged(Location locations)
{
updateLocation(locations);
}
public void onProviderDisabled(String arg0)
{
// TODO Auto-generated method stub
}
public void onProviderEnabled(String arg0)
{
// TODO Auto-generated method stub
}
public void onStatusChanged(String arg0, int arg1, Bundle arg2)
{
// TODO Auto-generated method stub
}
};
locationManager.requestLocationUpdates(provider, time, distance, myLocationListener);
}
/////////////////////////////////////////////////////////////////////////////////
public void findLocation()
{
gpsProvider = locationManager.getProvider(providerName);
//String bestProvider = locationManager.getBestProvider(criteria, true);
Location locations = locationManager.getLastKnownLocation(providerName);
updateLocation(locations);
}
public void updateLocation(Location locations)
{
if (locations != null)
{
Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
double latitude = locations.getLatitude();
double longitude = locations.getLongitude();
List<Address> addresses = null;
Geocoder GCoder = new Geocoder(this, Locale.getDefault());
try
{
addresses = GCoder.getFromLocation(latitude, longitude, 10);
Address first = addresses.get(0);
Log.d("ADDRESS", first.toString());
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
This, to me, should print the value "first" into LogCat but it doesn't seem to actually display anything.
I have the required permission in the manifest so that is not the issue.
Any help that can be provided is great, thank you.

Use this code
See Updated Code
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
String provider = locationManager.getBestProvider(new Criteria(), true);
Location locations = locationManager.getLastKnownLocation(provider);
List<String> providerList = locationManager.getAllProviders();
if(null!=locations && null!=providerList && providerList.size()>0){
double longitude = locations.getLongitude();
double latitude = locations.getLatitude();
Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
try {
List<Address> listAddresses = geocoder.getFromLocation(latitude, longitude, 1);
if(null!=listAddresses&&listAddresses.size()>0){
String _Location = listAddresses.get(0).getAddressLine(1);
}
} catch (IOException e) {
e.printStackTrace();
}
}

Related

How to get address from latitude and longitude?

I have implemented this code to display address based on GPS. The latitude and longitude are working fine (appear on the screen) however, for the address its stands "no address found". Please have look at this code and point any errors. Thanks
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_find__location);
LocationManager locationManager;
String context = Context.LOCATION_SERVICE;
locationManager =(LocationManager)getSystemService(context);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
String provider = locationManager.getBestProvider(criteria, true);
//String provider = LocationManager.GPS_PROVIDER;
Location location = locationManager.getLastKnownLocation(provider);
updateWithNewLocation(location);
locationManager.requestLocationUpdates(provider, 2000, 10, locationListener);
//buttons assigned
Button mainMenuBtn = (Button) findViewById(id.mainMenuBtn);
mainMenuBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
private final LocationListener locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
updateWithNewLocation(location);
}
#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) {
updateWithNewLocation(null);
}
};
private void updateWithNewLocation(Location location) {
String latLong;
TextView myLocationText;
myLocationText = (TextView)findViewById(R.id.myLocationText);
String addressString = "no address found";
if(location != null){
double lat = location.getLatitude();
double lng = location.getLongitude();
latLong = "Lat: "+lat+"\nLong: "+lng;
//double latitude = location.getLatitude();
//double longitude = location.getLongitude();
Geocoder gc = new Geocoder(this,Locale.getDefault());
try{
List<Address> addresses = gc.getFromLocation(lat, lng, 1);
StringBuilder sb = new StringBuilder();
if (addresses.size() > 0){
Address address = addresses.get(0);
for(int i=0; i < address.getMaxAddressLineIndex(); i++)
sb.append(address.getAddressLine(i)).append("\n");
sb.append(address.getLocality()).append("\n");
sb.append(address.getPostalCode()).append("\n");
sb.append(address.getCountryName());
}
addressString = sb.toString();
}catch (IOException e){}
}else{
latLong = "No location found";
}
myLocationText.setText("Your coordinates are:\n"+latLong + "\n"+addressString);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.find__location, menu);
return true;
}
}
I have had the same issue which was pretty annoying. Some answers suggested that geocoder does not always return a value so you have to loop some. However, this is not a good approach as you may never get a value, which sometimes is the case. Thus, what I have done in my project was to use google's reverse geocoding api. Idea is same but methodology is different.
This is the api page: https://developers.google.com/maps/documentation/geocoding/
Check the first answer here : Android Geocoder getFromLocationName always returns null
Hope this helps
I prefer to get address using google geocoding API, by sending lat lon params, you'll get some informations
https://developers.google.com/maps/documentation/geocoding/

adding AsyncTask for searching location

so I am making an application to get current position. The code below is working fine
String stringAddress = "";
public void getLocation(View view){
final LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria kriteria = new Criteria();
kriteria.setAccuracy(Criteria.ACCURACY_FINE);
kriteria.setAltitudeRequired(false);
kriteria.setBearingRequired(false);
kriteria.setCostAllowed(true);
kriteria.setPowerRequirement(Criteria.POWER_LOW);
final String provider = lm.getBestProvider(kriteria, true);
final Location lokasi = lm.getLastKnownLocation(provider);
updateWithNewLocation(lokasi);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 5, ll);
edittext_position.setText(stringAddress);
}
private void updateWithNewLocation(Location
if(lokasi != null){
double lat = lokasi.getLatitude();
double lng = lokasi.getLongitude();
Geocoder gc = new Geocoder(this, Locale.getDefault());
try{
List addresses = gc.getFromLocation(lat, lng, 1);
StringBuilder sb = new StringBuilder();
if(addresses.size()>0){
Address address = addresses.get(0);
sb.append(address.getAddressLine(0));
stringAddress= sb.toString();
}
} catch (Exception e){
}
}
}
private final LocationListener ll = new LocationListener() {
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public void onProviderEnabled(String provider) {
}
public void onProviderDisabled(String provider) {
updateWithNewLocation(null);
}
public void onLocationChanged(Location location) {
updateWithNewLocation(location);
}
}
but the problem is everytime I call getLocation() function, the application hang for a couple second before returning the result. I know to solve this problem using aSyncTask but I don't know how to start. Appreciate your help.
Thank you
It's snippet from my application:
public void getCurrentLocation(final ListenerGetCurrentLocation listenerGetCurrentLocation) {
new AsyncTask<Void, Void, List<Address>>() {
#Override
protected List<Address> doInBackground(Void... voids) {
Geocoder geo = new Geocoder(instance);
List<Address> listAddresses = null;
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, true);
if (bestProvider == null) {
bestProvider = LocationManager.NETWORK_PROVIDER;
}
Location location = locationManager.getLastKnownLocation(bestProvider);
try {
if (location != null) {
listAddresses = geo.getFromLocation(location.getLatitude(),
location.getLongitude(),
1);
}
} catch (IOException e) {
e.printStackTrace();
}
return listAddresses;
}
public void onPostExecute(List<Address> listAddresses) {
Address _address = null;
if ((listAddresses != null) && (listAddresses.size() > 0)) {
_address = listAddresses.get(0);
GeoPoint currentPosition = new GeoPoint(((int)(_address.getLatitude() * 1E6)),
((int)(_address.getLongitude() * 1E6)));
}
}
}.execute();
}
requestLocationUpdates() is asynchronous, it doesn't block your app. It polls the location in the background, then it calls the listener.
However, gc.getFromLocation() is not. This is probably the cause of your lag
Create a new AsyncTask, Eclipse will propose you to override those methods
#Override
protected List<String> doInBackground(String... params) {
// this is done in the background so it won't block the UI. The return type must be set to List<String> (I think default is just String)
return gc.getFromLocation()
}
#Override
protected void onPostExecute(List<String> adresses) {
// called when the GC work is finished. You can now use your list of addresses and display them
}
Don't forget to call execute() on your task.

Android GPS is returning null location

I have written code in that if GPS is disabled it will be enabled by code and try to get Location from gps but I am getting a null value. Below is my code
public void getValue() {
LocationManager mlocManager = (LocationManager) MySettings.this.getSystemService(Context.LOCATION_SERVICE);
boolean gpsEnabled = mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
System.out.println("GPS IS "+gpsEnabled);
if (!gpsEnabled) {
String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if (!provider.contains("gps")) { // if gps is disabled
final Intent poke = new Intent();
poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
sendBroadcast(poke);
}
}
SimpleDateFormat sdfDate = new SimpleDateFormat("MM/dd/yyyy");
try {
getBatteryLevel();
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, MySettings.this);
Location location = mlocManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
mLocation = location;
if (location != null) {
lat = location.getLatitude();
lon = location.getLongitude();
address = getAddress();
alt = location.getAltitude();
if (meterFootFlag) {
diameter = location.getAccuracy();
} else
diameter = location.getAccuracy() / 3.28084;
} else {
lat = 0.0;
lon = 0.0;
alt = 0.0;
}
} catch (Exception e) {
lat = 0.0;
lon = 0.0;
alt = 0.0;
}
Also I have added permission in manifest file
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
but I am getting a null value for the location.
Any ideas on how I can get the location?
Your code is correct just wait until GPs get altitude from a satellite it may take mroe than 1 minute.
try:
public Location showLocation(){
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
//Class model, save latitude and longitude
NavegadorCoordenadas locate = new NavegadorCoordenadas();
Criteria crit = new Criteria();
crit.setAccuracy(Criteria.ACCURACY_FINE);
String provider = lm.getBestProvider(crit, false);
Location loc = getLastKnownLocation(lm);
locate.setLatitude(loc.getLatitude());
locate.setLongitude(loc.getLongitude());
return loc;
}
private Location getLastKnownLocation(LocationManager location) {
List<String> providers = location.getProviders(true);
Location bestLocation = null;
for (String provider : providers) {
Location l = location.getLastKnownLocation(provider);
if (l == null) {
continue;
}
if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) {
bestLocation = l;
}
}
if (bestLocation == null) {
return null;
}
return bestLocation;
}
Make sure that you are checking on DEVICE only.. In Emulator it will give Null Values for GPS as it is running in the system so it doesnot have permission for GPS
locationMangaer = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if(!provider.contains("gps")){ //if gps is disabled
final Intent poke = new Intent();
poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
sendBroadcast(poke);
}
locationListener = new MyLocationListener();
locationMangaer.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10, 10,
locationListener);
Now make MyLocationListener class in same activity.
private class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location loc) {
String longitude = "Longitude: " +loc.getLongitude();
String latitude = "Latitude: " +loc.getLatitude();
/*----------to get City-Name from coordinates ------------- */
String cityName=null;
Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
List<Address> addresses;
try {
addresses = gcd.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1);
if (addresses.size() > 0) {
System.out.println(addresses.get(0).getLocality());
cityName=addresses.get(0).getLocality();
System.out.println("MESSAGE:"+cityName);
}
} catch (IOException e) {
e.printStackTrace();
}
String s = longitude+"\n"+latitude+"\t city name:"+cityName;
Log.v("OUTPUT, s);
}
#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
}
}
Run your application in Actual device.
you can figure out that automatic start GPS and see console logcat.
Make sure to open Permissions through the
Settings--> Applications-->YourApp-->permissions
And another reason could be delay, it takes time to connect to network, somethimes more than a minute

reverse geocoding not working

i written following code to get current location. although I m testing it in emulator with different latitude and longitude. But it cant convert the lattitude and longitude in real location.
public class LocationFindingActivity extends Activity {
/** Called when the activity is first created. */
EditText et;
LocationManager locationManager;
String provider;
LocationListener locationListener;
Location currentLocation;
String addressString="";
String longlattString="";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
et=(EditText)findViewById(R.id.locationTXT);
locationManager =(LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
provider = locationManager.getBestProvider(criteria, true);
currentLocation=locationManager.getLastKnownLocation(provider);
et.setText(addressString);
locationListener =new LocationListener() {
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onLocationChanged(Location arg0) {
// TODO Auto-generated method stub
updateWithNewLocation(currentLocation);
}
};
updateWithNewLocation(currentLocation);
locationManager.requestLocationUpdates(provider, 2000, 10,locationListener)
}
private void updateWithNewLocation(Location location) {
if (location != null)
{
double lat = location.getLatitude();
double lng = location.getLongitude();
longlattstring="Lattitude :"+lat+"Longitude :"+lng;
Geocoder gc = new Geocoder(this, Locale.getDefault());
try
{
List<Address> addresses = gc.getFromLocation(lat, lng, 1);
StringBuilder sb = new StringBuilder();
//Toast.makeText(this, "Problem1", 2000).show();
if (addresses.size() > 0)
{
Address address = addresses.get(0);
for (int i = 0; i < address.getMaxAddressLineIndex(); i++)
sb.append(address.getAddressLine(i)).append("\n");
sb.append(address.getLocality()).append("\n");
Toast.makeText(this, "Problem2", 2000).show();
sb.append(address.getPostalCode()).append("\n");
sb.append(address.getCountryName());
}
addressString = sb.toString();
}
catch (IOException e)
{
Toast.makeText(this, "Problem Catch", 2000).show();
}
}
else
{
addressString = "No location found";
}
et.setText(addressString);
}
}
I am getting problem in this line
List addresses = gc.getFromLocation(lat, lng, 1);
the statement doesn't return anything.
It's a known bug which they never fixed see service not avavilable.I think you will find that it works in the the API level 7 emulator.

using geocoder with myLocationOverlay

i try to get the current zip code from the longitude and latitude which MyLocationOverlay delivers and set this to a EditView on my Activity.
The Activity crashs when i try to get the longitude and latitude from MyLocationOverlay.
Whats wrong with this code?
Regards,
float
LogCat output: http://codepaste.net/vs6itk
Line 59 is the following line:
double currentLatitude = myLocationOverlay.getMyLocation().getLatitudeE6();
Here is my Code:
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.partner_suche);
final EditText tView = (EditText) findViewById(R.id.editTextPLZ);
final MapView mView = (MapView) findViewById(R.id.mapview);
mView.getController().setZoom(14);
List<Overlay> mapOverlays = mView.getOverlays();
myLocationOverlay = new MyCustomLocationOverlay(this, mView);
mapOverlays.add(myLocationOverlay);
myLocationOverlay.enableMyLocation();
myLocationOverlay.enableCompass();
myLocationOverlay.runOnFirstFix(new Runnable() {
public void run() {
mView.getController().animateTo(myLocationOverlay.getMyLocation());
}
});
Geocoder gc = new Geocoder(this, Locale.getDefault());
double currentLatitude = myLocationOverlay.getMyLocation().getLatitudeE6();
double currentLongitute = myLocationOverlay.getMyLocation().getLongitudeE6();
try
{
List<Address> addresses = gc.getFromLocation(currentLatitude, currentLongitute, 1);
if (addresses.size() > 0)
{
tView.setText(addresses.get(0).getLocality());
}
} catch (IOException e)
{
}
}
EDIT:
I created a LocationListener to get my current location. Now the part crashes where i try to run gc.getFromLocation(latitude, longitude, 1); I can't read the Exception? :/
LocationManager locationManager;
String context = Context.LOCATION_SERVICE;
locationManager = (LocationManager)getSystemService(context);
String provider = LocationManager.GPS_PROVIDER;
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
updateWithNewLocation(location);
}
public void onProviderDisabled(String provider){
updateWithNewLocation(null);
}
public void onProviderEnabled(String provider){ }
public void onStatusChanged(String provider, int status,Bundle extras){ }
};
locationManager.requestLocationUpdates(provider, 0, 0, locationListener);
private void updateWithNewLocation(Location location) {
final EditText tView = (EditText) findViewById(R.id.editTextPLZ);
double latitude = location.getLatitude();
double longitude = location.getLongitude();
Geocoder gc = new Geocoder(this, Locale.getDefault());
if (location != null) {
try
{
List<Address> addresses = gc.getFromLocation(latitude, longitude, 1);
if (addresses.size() > 0)
{
Address address = addresses.get(0);
for (int i = 0; i < address.getMaxAddressLineIndex(); i++){
tView.setText(address.getPostalCode());
}
}
} catch (Exception e)
{
}
}
}
If you are using an emulator API level 8 or 9, and getting the exception:
java.io.IOException: Service not Available
then it is a known bug, see service not available
It works OK on real devices and emulator level 7 though. ( You should probably put a trap on addresses being null too, though this won't make the geocoder work!)
Most likely the location being returned from
myLocationOverlay.getMyLocation()
or
Location location = locationManager.getLastKnownLocation(provider);
is NULL. Likely due to your application not yet having received a location fix, and having no previously saved locations.
Try moving the code block where you do the geocoding into your runnable that runs after receiving a fix. Like this:
myLocationOverlay.runOnFirstFix(new Runnable() {
public void run() {
Location loc = myLocationOverlay.getMyLocation();
if (loc != null) {
mView.getController().animateTo(loc);
Geocoder gc = new Geocoder(this, Locale.getDefault());
double currentLatitude = loc.getLatitudeE6();
double currentLongitute = loc.getLongitudeE6();
try
{
List<Address> addresses = gc.getFromLocation(currentLatitude, currentLongitute, 1);
if (addresses.size() > 0)
{
tView.setText(addresses.get(0).getLocality());
}
} catch (IOException e)
{
}
}
}
});

Categories

Resources