my following coding for getting current address means location is failed if i try to set address to the TextBox but when i put that code inside a onClick event of Button that works properly
This is Coding is Working When it is inside a onCLick event
import java.io.IOException;
import java.util.*;
import android.widget.*;
import android.view.View;
import android.view.View.OnClickListener;
import android.app.Activity;
import android.os.Bundle;
import android.location.*;
import android.content.*;
public class location extends Activity {
Button addressButton;
TextView addressText;
Location currentLocation;
double currentLatitude;
double currentLongitude;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.location);
addressText = (TextView)findViewById(R.id.addressText);
addressButton = (Button)findViewById(R.id.addressButton);
this.addressText.setText("ready");
LocationManager locationManager =
(LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
updateLocation(location);
}
public void onStatusChanged(
String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
this.addressButton.setOnClickListener(new OnClickListener() {
public void onClick(View v){
try{
Geocoder gcd = new Geocoder(location.this, Locale.getDefault());
List<Address> addresses =
gcd.getFromLocation(currentLatitude, currentLongitude,100);
StringBuilder result = new StringBuilder();
if (addresses.size() > 0) {
Address address = addresses.get(0);
int maxIndex = address.getMaxAddressLineIndex();
for (int x = 0; x <= maxIndex; x++ ){
result.append(address.getAddressLine(x));
//result.append(",");
}
}
addressText.setText(result.toString());
Intent send_add = new Intent();
send_add.putExtra("address",result.toString());
}
catch(IOException ex){
addressText.setText(ex.getMessage().toString());
}
}
});
}
void updateLocation(Location location){
currentLocation = location;
currentLatitude = currentLocation.getLatitude();
currentLongitude = currentLocation.getLongitude();
}}
This is Coding not Working here i dont want to use Button when i open this activity it must display direct address means it should be Set to the Textview
public class location extends Activity {
Button addressButton;
TextView addressText;
Location currentLocation;
double currentLatitude;
double currentLongitude;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.location);
addressText = (TextView)findViewById(R.id.addressText);
addressButton = (Button)findViewById(R.id.addressButton);
this.addressText.setText("ready");
LocationManager locationManager =
(LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
updateLocation(location);
}
public void onStatusChanged(
String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
try{
Geocoder gcd = new Geocoder(location.this, Locale.getDefault());
List<Address> addresses =
gcd.getFromLocation(currentLatitude, currentLongitude,100);
StringBuilder result = new StringBuilder();
if (addresses.size() > 0) {
Address address = addresses.get(0);
int maxIndex = address.getMaxAddressLineIndex();
for (int x = 0; x <= maxIndex; x++ ){
result.append(address.getAddressLine(x));
//result.append(",");
}
}
addressText.setText(result.toString());
Intent send_add = new Intent();
send_add.putExtra("address",result.toString());
}
catch(IOException ex){
addressText.setText(ex.getMessage().toString());
}
}
void updateLocation(Location location){
currentLocation = location;
currentLatitude = currentLocation.getLatitude();
currentLongitude = currentLocation.getLongitude();
}}
Here i just made a small change but not working
I have updated your code and it is working correct now :
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
currentLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); //added by me
// Geocoder gcd = new Geocoder(location.this, Locale.getDefault());
try{
// Geocoder gcd = new Geocoder(location.this, Locale.getDefault());
//List<Address> addresses =
// gcd.getFromLocation(currentLatitude, currentLongitude,100);
List<Address> addresses = new Geocoder(location.this,Locale.getDefault()).getFromLocation(currentLocation.getLatitude(), currentLocation.getLongitude(), 1); // changed
StringBuilder result = new StringBuilder();
if (addresses.size() > 0) {
Address address = addresses.get(0);
int maxIndex = address.getMaxAddressLineIndex();
for (int x = 0; x <= maxIndex; x++ ){
result.append(address.getAddressLine(x));
//result.append(",");
}
}
addressText.setText(result.toString());
Intent send_add = new Intent();
send_add.putExtra("address",result.toString());
}
catch(IOException ex){
addressText.setText(ex.getMessage().toString());
}
Related
I'm working on GPS based application that gets the address based on GPS provider but sometimes it doesn't work due to lack of signal like as at underground parking or similar places. So in such situtation i want to take the address through Network provider and send SMS via sendSMS() method. It has to repeat every 10 mints and call the sendSMS() method with updated Location.
The code for getting GPS location is below could you please suggest me to edit it according to my need?
public class WPGActivity extends Activity {
ImageButton start;
Button login;
String ADDRESS, LOCATION;
TextView addressText, locationText;
Location currentLocation;
double currentLatitude;
double currentLongitude;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
start=(ImageButton)findViewById(R.id.imageButton1);
login=(Button)findViewById(R.id.button1);
addressText = (TextView)findViewById(R.id.addressText);
locationText = (TextView)findViewById(R.id.locationText);
myLocation();
// if(ACTIVE_MODE==1) startApp();
start.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
getAddress(); // to get address
sendSMS(); // to send sms
sendEmail(); // to send email
}
});
}
public void myLocation(){
LocationManager locationManager =
(LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
updateLocation(location);
}
public void onStatusChanged(
String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000*60*5, 30, locationListener);
}
public void getAddress(){
try{
Geocoder gcd = new Geocoder(this, Locale.getDefault());
List<Address> addresses =
gcd.getFromLocation(currentLatitude, currentLongitude,100);
if (addresses.size() > 0) {
StringBuilder result = new StringBuilder();
for(int i = 0; i < addresses.size(); i++){
Address address = addresses.get(i);
int maxIndex = address.getMaxAddressLineIndex();
for (int x = 0; x <= maxIndex; x++ ){
result.append(address.getAddressLine(x));
result.append(",");
}
result.append(address.getLocality());
result.append(",");
result.append(address.getPostalCode());
result.append("\n\n");
}
ADDRESS = result.toString();
addressText.setText(ADDRESS);
}
}
catch(IOException ex){
ADDRESS= ex.getMessage().toString();
addressText.setText(ADDRESS);
}
}
void updateLocation(Location location){
currentLocation = location;
currentLatitude = currentLocation.getLatitude();
currentLongitude = currentLocation.getLongitude();
locationText.setText(LOCATION);
}
}
I am trying to Set Location but getting NullPointerException , i have Provided android.permission.ACCESS_COARSE_LOCATION , android.permission.ACCESS_FINE_LOCATION
In manifest file my Source code is as Follow , i am getting Null pointer on
List<Address> addresses = new Geocoder(LocationDemo.this,Locale.getDefault()).getFromLocation(currentLocation.getLatitude(), currentLocation.getLongitude(), 1);
My Coding is As Follow
import java.io.IOException;
import java.util.*;
import android.widget.*;
import android.app.Activity;
import android.os.Bundle;
import android.location.*;
import android.content.*;
public class LocationDemo extends Activity {
TextView addressText;
Location currentLocation;
double currentLatitude;
double currentLongitude;
String store;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
addressText = (TextView)findViewById(R.id.addressText);
addressText.setText("ready");
LocationManager locationManager =
(LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
updateLocation(location);
}
public void onStatusChanged(
String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
currentLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
try{
List<Address> addresses = new Geocoder(LocationDemo.this,Locale.getDefault()).getFromLocation(currentLocation.getLatitude(), currentLocation.getLongitude(), 1);
StringBuilder result = new StringBuilder();
if (addresses.size() > 0) {
Address address = addresses.get(0);
int maxIndex = address.getMaxAddressLineIndex();
for (int x = 0; x <= maxIndex; x++ ){
result.append(address.getAddressLine(x));
//result.append(",");
}
}
addressText.setText(result.toString());
Intent send_add = new Intent();
send_add.putExtra("address",result.toString());
store = addressText.getText().toString();
}
catch(IOException ex)
{
addressText.setText(ex.getMessage().toString());
}
}
void updateLocation(Location location){
currentLocation = location;
currentLatitude = currentLocation.getLatitude();
currentLongitude = currentLocation.getLongitude();
}
}
i am importing this code in application that extends Service that is trying to obtain Address on startup of service
Might be you are getting current location as null. as it takes some time to calculate the location .if this is the case , try this
import java.io.IOException;
import java.util.*;
import android.widget.*;
import android.app.Activity;
import android.os.Bundle;
import android.location.*;
import android.content.*;
public class LocationDemo extends Activity {
TextView addressText;
Location currentLocation;
double currentLatitude;
double currentLongitude;
String store;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
addressText = (TextView)findViewById(R.id.addressText);
addressText.setText("ready");
LocationManager locationManager =
(LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
setAddress(location)
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
}
public void setAddress(Location location){
currentLocation = location;
currentLatitude = currentLocation.getLatitude();
currentLongitude = currentLocation.getLongitude();
try{
List<Address> addresses = new Geocoder(LocationDemo.this,Locale.getDefault()).getFromLocation(currentLocation.getLatitude(), currentLocation.getLongitude(), 1);
StringBuilder result = new StringBuilder();
if (addresses.size() > 0) {
Address address = addresses.get(0);
int maxIndex = address.getMaxAddressLineIndex();
for (int x = 0; x <= maxIndex; x++ ){
result.append(address.getAddressLine(x));
//result.append(",");
}
}
addressText.setText(result.toString());
Intent send_add = new Intent();
send_add.putExtra("address",result.toString());
store = addressText.getText().toString();
}
catch(IOException ex)
{
addressText.setText(ex.getMessage().toString());
}
}
}
LocationListener[] mLocationListeners = new LocationListener[] {
new LocationListener(LocationManager.GPS_PROVIDER),
new LocationListener(LocationManager.NETWORK_PROVIDER) };
try this code in your Location Listener.
Of course you're getting a null pointer because currentLocation is null till onLocationChanged is called. Thus you have to put your code there:
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// put your code here once you have the location
}
public void onStatusChanged(
String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
I want to get the current location with name. I did coding for get current location (lat,lang), how can I show the relative place name?
(ie) 13.006389 - 80.2575 : Adyar,Chennai,India
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new LocationListener() {
public void onStatusChanged(String provider, int status, Bundle extras) {
// called when the location provider status changes. Possible status: OUT_OF_SERVICE, TEMPORARILY_UNAVAILABLE or AVAILABLE.
}
public void onProviderEnabled(String provider) {
// called when the location provider is enabled by the user
}
public void onProviderDisabled(String provider) {
// called when the location provider is disabled by the user. If it is already disabled, it's called immediately after requestLocationUpdates
}
public void onLocationChanged(Location location) {
double latitute = location.getLatitude();
double longitude = location.getLongitude();
// do whatever you want with the coordinates
}
});
This will convert the lat & lng into String Address and i have set it in the text field for your example. This is done by using the concept of Reverse Geocoding & there is a class called Geocoder in Android.
// Write the location name.
//
try {
Geocoder geo = new Geocoder(this.getApplicationContext(), Locale.getDefault());
List<Address> addresses = geo.getFromLocation(latitude, longitude, 1);
if (addresses.isEmpty()) {
yourtextboxname.setText("Waiting for Location");
}
else {
yourtextboxname.setText(addresses.get(0).getFeatureName() + ", " + addresses.get(0).getLocality() +", " + addresses.get(0).getAdminArea() + ", " + addresses.get(0).getCountryName());
}
}
Here is code to get current location and draw it on Google Maps
public class Showmap extends MapActivity {
private MapView mapView;
private MapController mapController;
private LocationManager locationManager;
private LocationListener locationListener;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.showmap);
LocationManager locationManager = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
locationListener = new GPSLocationListener();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
0, locationListener);
mapView = (MapView) findViewById(R.id.mapView);
// enable Street view by default
mapView.setStreetView(true);
// enable to show Satellite view
// mapView.setSatellite(true);
// enable to show Traffic on map
// mapView.setTraffic(true);
mapView.setBuiltInZoomControls(true);
mapController = mapView.getController();
mapController.setZoom(16);
}
protected boolean isRouteDisplayed() {
return false;
}
private class GPSLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
if (location != null) {
GeoPoint point = new GeoPoint(
(int) (location.getLatitude() * 1E6),
(int) (location.getLongitude() * 1E6));
mapController.animateTo(point);
mapController.setZoom(16);
// add marker
MapOverlay mapOverlay = new MapOverlay();
mapOverlay.setPointToDraw(point);
List<Overlay> listOfOverlays = mapView.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(mapOverlay);
String address = ConvertPointToLocation(point);
Toast.makeText(getBaseContext(), address, Toast.LENGTH_SHORT)
.show();
mapView.invalidate();
}
}
public String ConvertPointToLocation(GeoPoint point) {
String address = "";
Geocoder geoCoder = new Geocoder(getBaseContext(),
Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocation(
point.getLatitudeE6() / 1E6,
point.getLongitudeE6() / 1E6, 1);
if (addresses.size() > 0) {
for (int index = 0; index < addresses.get(0)
.getMaxAddressLineIndex(); index++)
address += addresses.get(0).getAddressLine(index) + " ";
Log.i(address, address);
}
} catch (IOException e) {
e.printStackTrace();
}
return address;
}
#Override
public void onProviderDisabled(String provider) {}
#Override
public void onProviderEnabled(String provider) {}
#Override
public void onStatusChanged(String provider,int status,Bundle extras){}
}
class MapOverlay extends Overlay {
private GeoPoint pointToDraw;
public void setPointToDraw(GeoPoint point) {
pointToDraw = point;
}
public GeoPoint getPointToDraw() {
return pointToDraw;
}
#Override
public boolean draw(Canvas canvas, MapView mapView, boolean shadow,
long when) {
super.draw(canvas, mapView, shadow);
// convert point to pixels
Point screenPts = new Point();
mapView.getProjection().toPixels(pointToDraw, screenPts);
// add marker
Bitmap bmp = BitmapFactory.decodeResource(getResources(),
R.drawable.marker);
// 24 is the height of image
canvas.drawBitmap(bmp, screenPts.x, screenPts.y - 24, null);
return true;
}
}
}
Use reverse geocoding,feed the latitude and longitude and get the address.
Geocoder geocoder = new Geocoder(this, Locale.ENGLISH);
try {
List<Address> addresses = geocoder.getFromLocation(LATITUDE, LONGITUDE, 1);
if(addresses != null) {
Address returnedAddress = addresses.get(0);
StringBuilder strReturnedAddress = new StringBuilder("Address:\n");
for(int i=0; i<returnedAddress.getMaxAddressLineIndex(); i++) {
strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
}
myAddress.setText(strReturnedAddress.toString());
}
else{
myAddress.setText("No Address returned!");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
myAddress.setText("Canont get Address!");
}
The phrase you're looking for is "Reverse Geocoding". Another question on StackOverflow discusses the same topic- You can use that one's selected answer :)
This is only for Hint add your code !
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
if (location != null) {
System.out.println("in onlocationchanged");
String locationString=location.convert(location.getLatitude(),1);
Toast.makeText(this,"locationString=="+locationString, Toast.LENGTH_LONG).show();
double lat = location.getLatitude();
double lng = location.getLongitude();
String currentLocation = "The location is changed to Lat: " + lat + " Lng: " + lng;
Toast.makeText(this,currentLocation, Toast.LENGTH_LONG).show();
use this two method
public double getLattitude() {
return lattitude;
}
}
public double getLongitude() {
return longitude;
public class MainActivity extends AppCompatActivity {
double latitude, longitude;
private TextView tvLocation;
private Button btnGetLocation;
private FusedLocationProviderClient locationProviderClient;
private Geocoder geocoder;
private List<Address> addresses;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
requestPermission();
locationProviderClient = LocationServices.getFusedLocationProviderClient(this);
tvLocation = findViewById(R.id.tv_location);
geocoder = new Geocoder(MainActivity.this, Locale.getDefault());
btnGetLocation = findViewById(R.id.btn_location);
btnGetLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (ActivityCompat.checkSelfPermission(MainActivity.this, ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
locationProviderClient.getLastLocation().addOnSuccessListener(MainActivity.this, new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
if (location != null) {
tvLocation.setText(location.toString());
latitude = location.getLatitude();
longitude = location.getLongitude();
try {
addresses = geocoder.getFromLocation(latitude, longitude, 1);
String addressLine1 = addresses.get(0).getAddressLine(0);
Log.e("line1", addressLine1);
String city = addresses.get(0).getLocality();
Log.e("city", city);
String state = addresses.get(0).getAdminArea();
Log.e("state", state);
String pinCode = addresses.get(0).getPostalCode();
Log.e("pinCode", pinCode);
String fullAddress = addressLine1 + ", " + city + ", " + state + ", " + pinCode;
tvLocation.setText(fullAddress);
} catch (IOException e) {
e.printStackTrace();
Log.e("MainActivity", e.getMessage());
}
}
}
});
}
});
}
private void requestPermission() {
ActivityCompat.requestPermissions(this, new String[]{ACCESS_FINE_LOCATION}, 1);
}
}
Here Is my code to get the current country Name.
private String getCountry() {
String country_name = null;
LocationManager lm = (LocationManager)getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
Geocoder geocoder = new Geocoder(getApplicationContext());
for(String provider: lm.getAllProviders()) {
#SuppressWarnings("ResourceType") Location location = lm.getLastKnownLocation(provider);
if(location!=null) {
try {
List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
if(addresses != null && addresses.size() > 0) {
country_name =addresses.get(0).getCountryName();
return country_name;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Toast.makeText(getApplicationContext(), country_name, Toast.LENGTH_LONG).show();
return null;
}
But don't forget to add this permission in the manifest file.
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
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)
{
}
}
}
});
This question already has answers here:
Geocoder.getFromLocation throws IOException on Android emulator
(7 answers)
Closed 6 months ago.
In the code below, I am getting the following exception
NO SERVICE AVAIALBLE
public class ds extends Activity {
LocationManager locationManager;
double lati,longi;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String location_context = Context.LOCATION_SERVICE;
locationManager = (LocationManager)getSystemService(location_context);
testProviders();
}
public void testProviders() {
TextView tv = (TextView)findViewById(R.id.myTextView);
StringBuilder sb = new StringBuilder("Enabled Providers:");
List<String> providers = locationManager.getProviders(true);
for (String provider : providers)
{
locationManager.requestLocationUpdates(provider, 1000, 0,new LocationListener()
{
public void onLocationChanged(Location location) {}
public void onProviderDisabled(String provider){}
public void onProviderEnabled(String provider){}
public void onStatusChanged(String provider, int status,
Bundle extras){}
});
sb.append("\n").append(provider).append(":");
Location location = locationManager.getLastKnownLocation(provider);
if (location != null)
{
double lat = location.getLatitude();
double lng = location.getLongitude();
sb.append(lat).append(",").append(lng);
lati=lat;
longi=lng;
Geocoder gcd = new Geocoder(ds.this, Locale.getDefault());
List<Address> addresses;
try {
addresses = gcd.getFromLocation(lati, longi, 1);
if (addresses.size() > 0)
} catch (IOException e) {
Toast.makeText(ds.this, "hi exception", 5000).show();
}
}
else {
sb.append("No Location");
}
}
tv.setText(sb);
}
}
Code for Reverse Geocoding , you can pass the lattitude and longitude according to your requirement......
public class MainActivity extends FragmentActivity {
static final LatLng DELHI = new LatLng(39.6985207, -104.8954315);
GoogleMap map;
Button btn_geo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activitymain);
map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
btn_geo=(Button)findViewById(R.id.btn_getAddress);
map.addMarker(new MarkerOptions().position(DELHI).icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher)));
// Move the camera instantly to hamburg with a zoom of 15.
map.moveCamera(CameraUpdateFactory.newLatLngZoom(DELHI, 15));
// Zoom in, animating the camera.
map.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);
btn_geo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Geocoder myLocation = new Geocoder(getApplicationContext(), Locale.getDefault());
try {
if(myLocation.isPresent())
{
List<Address> addresses=null ;
addresses = myLocation.getFromLocation(39.6985207, -104.8954315, 1);
System.out.println(".................."+addresses);
StringBuilder sb = new StringBuilder();
if (addresses.size() > 0)
{
Address address = addresses.get(0);
sb.append(address.getAddressLine(0)).append("\n");
sb.append(address.getLocality()).append("\n");
sb.append(address.getPostalCode()).append("\n");
sb.append(address.getCountryName());
Toast.makeText(getApplicationContext(), sb,Toast.LENGTH_LONG).show();
}
}
else
Toast.makeText(getApplicationContext(), "Not present",Toast.LENGTH_SHORT).show();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}