in android i'm getting IOException in Geocoder - android

it throw IOException if the network is unavailable or any other I/O problem occurs. It need internet connection to use Geocoder.
public class MainActivity extends Activity {
double LATITUDE = 37.42233;
double LONGITUDE = -122.083;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView myLatitude = (TextView)findViewById(R.id.mylatitude);
TextView myLongitude = (TextView)findViewById(R.id.mylongitude);
TextView myAddress = (TextView)findViewById(R.id.myaddress);
myLatitude.setText("Latitude: " + String.valueOf(LATITUDE));
myLongitude.setText("Longitude: " + String.valueOf(LONGITUDE));
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) {
e.printStackTrace();
myAddress.setText("Cannot get Address!");//and tell me what is
}
}
}
anyone has any idea?
I have managed to do it with Emulator 2.1 api 8, but then the reverse geocoding always give an empty result. anyone could confirm my code?
log cat
06-03 10:59:24.689: W/System.err(4129):java.io.IOException: Service not Available
:at android.location.Geocoder.getFromLocation(Geocoder.java:136)
:at com.example.gprsonandoff.MainActivity.city(MainActivity.java:74)
:at com.example.gprsonandoff.MainActivity.onCreate(MainActivity.java:44)
:android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
:at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)

It seems to be a prob faced by many. Check this.
You can try using GeoCoding APIs if using Geocoder doesn't work out even if internet connection is there.

I Reboot My Android Device and Error is gone.

Related

Reverse GeoCoordinate Class gives Location Not found error

i m using google Reverse Geocoding API in my app, i m succussfully able to get get coordinate using google geolocation API. Now i m trying to get Location Name from Reverse Geocoding API , but always returns Location not found error
here is my code:
Geocoder geocoder= new Geocoder(MainActivity.this, Locale.ENGLISH);
if(geocoder.isPresent()){
List<Address> list;
try {
list = geocoder.getFromLocation(37.42279, -122.08506,1);
Address address = list.get(0);
Log.d("this is working","thsi sis working");
StringBuffer str = new StringBuffer();
str.append("Name: " + address.getLocality() + "\n");
str.append("Sub-Admin Ares: " + address.getSubAdminArea() + "\n");
str.append("Admin Area: " + address.getAdminArea() + "\n");
str.append("Country: " + address.getCountryName() + "\n");
str.append("Country Code: " + address.getCountryCode() + "\n");;
String strAddress = str.toString();
JsonDatas.setText(strAddress);
Log.d("Address", strAddress);
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
i have several question
how google know that which app requested the API and how google determine of Quota that app. in google API developer Console, google gave Quota for app API
Why i m getting location not found error but searching on google map location is showing
do i need to add google Geocoder APi key into my app - right now i m only Geolocation API key using for retrieve Coordinates
Please correct me if i m wrong, Please give suggestion so my code will work fine
thanks
Make sure you have latest Google play library in your project. I am using this code and working for me.
private class ReverseGeocodingTask extends AsyncTask<LatLng, Void, String> {
Context mContext;
public ReverseGeocodingTask(Context context) {
super();
mContext = context;
}
// Finding address using reverse geocoding
#Override
protected String doInBackground(LatLng... params) {
Geocoder geocoder = new Geocoder(mContext);
double latitude = params[0].latitude;
double longitude = params[0].longitude;
List<Address> addresses = null;
String addressText = "";
try {
addresses = geocoder.getFromLocation(latitude, longitude, 1);
Thread.sleep(500);
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
addressText = String.format(
"%s",
address.getMaxAddressLineIndex() > 0 ? address
.getAddressLine(1) : "", "", "");
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
return addressText;
}
#Override
protected void onPostExecute(String addressText) {
}
}
Where LatLng is Latitude and longitute, check this for doc.
and to use write down new ReverseGeocodingTask(this).execute(latlng); where you want to get data.
Make sure you are adding permission into your manifest file.
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />

Android Reverse Geocoding

I'm trying to get an address from a location. I'm doing so inside a asynctask inside a Fragement. All the other code works fine (checking an API and setting some UI stuff based on it) but this section to do the geocoding just won't. I followed an example from elsewhere on StackOverflow (can't remember the exact topic).
TextView locTxt = (TextView) findViewById(R.id.locationText);
Geocoder geocoder;
List<Address> addresses;
Double x = 55.971627;
Double y = -3.602585;
try
{
geocoder = new Geocoder(getActivity(), Locale.ENGLISH);
addresses = geocoder.getFromLocation(x, y, 1);
StringBuilder str = new StringBuilder();
if (geocoder.isPresent())
{
Toast.makeText(getApplicationContext(),
"geocoder present", Toast.LENGTH_SHORT).show();
Address returnAddress = addresses.get(0);
String localityString = returnAddress.getLocality();
String city = returnAddress.getCountryName();
String region_code = returnAddress.getCountryCode();
String zipcode = returnAddress.getPostalCode();
str.append(localityString + "");
str.append(city + "" + region_code + "");
str.append(zipcode + "");
locTxt.setText(str);
}
else
{
Toast.makeText(getApplicationContext(), "geocoder not present", Toast.LENGTH_SHORT).show();
}
} catch (IOException e) {}
When it gets to the if statement for geocoder.isPresent() is fails the if and just continues on with the rest of the program.
The issue is with Android Emulator. Even when you set coordinates via the command line the emulator will not preform GeoCoding code and therefore fails on my check if GeoCoder present. Works just fine on a physical device.

Can't get the Address from Geocoder

I have created simple code just for getting address from string location. Code brakes at starred line. Why ?? if I print the exception : Service not Available
List<Address> address;
String myAddress = "Vilnius";
Geocoder coder = new Geocoder(getApplicationContext(), Locale.getDefault());
System.out.println("coder : :" + coder);
**address = coder.getFromLocationName(myAddress, 1);**
ObjLoc1adr = coder.getFromLocationName(ObjLoc1String, 1);
ObjLoc2adr = coder.getFromLocationName(ObjLoc2String, 1);
Because of this you should always wrap that code in a try block to catch an IOException. There is no guarantee that the Geocoder always find a location or the service is reachable. This hasn't to be a fault of your code or device. A simple connection problem or timeout is enough to brake your App.
To be save have something like this:
if(GeoCoder.isPresent()) {
Geocoder geocoder = new Geocoder(this);
String myAddress = "Vilnius";
List<Address> addresses = null;
try {
address = geocoder.getFromLocationName(myAddress, 1);
if (!addresses.isEmpty()) {
Address address = list.get(0);
// do something with your address
} else {
// No results for your location
}
} catch (IOException e) {
e.printStackTrace();
}
}

how to convert the latitude and longitudein to postal address

how to convert the latitude and longitude in to postal address. i am not possible to use mapview to get geopoint.I wanted to convert latitude and longitude in address without use of mapview
This is called Reverse Geocoding, there are number of services that you can use including Google, Yahoo and Bing
See this article for free Geocoding services
Android has GeoCoder class for this :
public String getAddress(double latitude, double longitude){
if (Geocoder.isPresent()) {
try {
Geocoder geocoder = new Geocoder(mContext, Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(latitude,longitude,1);
if(addresses != null && addresses.size() > 0) {
Address first = addresses.get(0);
StringBuilder sb = new StringBuilder();
if(first.getMaxAddressLineIndex() > 0){
sb.append(first.getAddressLine(0) + ", ");
}
sb.append(first.getLocality() + ", ");
sb.append(first.getCountryName());
return sb.toString();
} catch (Exception e) {
Log.e("MyAPP", "Reverse geo lookup failed", e);
return "Unavailable"
}
} else {
return "unavailable";
}
}
Go to project properties > Android > set project build target to Google

Android: Reverse geocoding - getFromLocation

I am trying to get an address based on the long/lat. it appears that something like this should work?
Geocoder myLocation = Geocoder(Locale.getDefault());
List myList = myLocation.getFromLocation(latPoint,lngPoint,1);
The issue is that I keep getting : The method Geocoder(Locale) is undefined for the type savemaplocation
Any assistance would be helpful. Thank you.
Thanks, I tried the context, locale one first, and that failed and was looking at some of the other constructors (I had seen one that had mentioned just locale). Regardless,
It did not work, as I am still getting : The method Geocoder(Context, Locale) is undefined for the type savemaplocation
I do have : import android.location.Geocoder;
The following code snippet is doing it for me (lat and lng are doubles declared above this bit):
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(lat, lng, 1);
Here is a full example code using a Thread and a Handler to get the Geocoder answer without blocking the UI.
Geocoder call procedure, can be located in a Helper class
public static void getAddressFromLocation(
final Location location, final Context context, final Handler handler) {
Thread thread = new Thread() {
#Override public void run() {
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
String result = null;
try {
List<Address> list = geocoder.getFromLocation(
location.getLatitude(), location.getLongitude(), 1);
if (list != null && list.size() > 0) {
Address address = list.get(0);
// sending back first address line and locality
result = address.getAddressLine(0) + ", " + address.getLocality();
}
} catch (IOException e) {
Log.e(TAG, "Impossible to connect to Geocoder", e);
} finally {
Message msg = Message.obtain();
msg.setTarget(handler);
if (result != null) {
msg.what = 1;
Bundle bundle = new Bundle();
bundle.putString("address", result);
msg.setData(bundle);
} else
msg.what = 0;
msg.sendToTarget();
}
}
};
thread.start();
}
Here is the call to this Geocoder procedure in your UI Activity:
getAddressFromLocation(mLastKownLocation, this, new GeocoderHandler());
And the handler to show the results in your UI:
private class GeocoderHandler extends Handler {
#Override
public void handleMessage(Message message) {
String result;
switch (message.what) {
case 1:
Bundle bundle = message.getData();
result = bundle.getString("address");
break;
default:
result = null;
}
// replace by what you need to do
myLabel.setText(result);
}
}
Don't forget to put the following permission in your Manifest.xml
<uses-permission android:name="android.permission.INTERNET" />
It looks like there's two things happening here.
1) You've missed the new keyword from before calling the constructor.
2) The parameter you're passing in to the Geocoder constructor is incorrect. You're passing in a Locale where it's expecting a Context.
There are two Geocoder constructors, both of which require a Context, and one also taking a Locale:
Geocoder(Context context, Locale locale)
Geocoder(Context context)
Solution
Modify your code to pass in a valid Context and include new and you should be good to go.
Geocoder myLocation = new Geocoder(getApplicationContext(), Locale.getDefault());
List<Address> myList = myLocation.getFromLocation(latPoint, lngPoint, 1);
Note
If you're still having problems it may be a permissioning issue. Geocoding implicitly uses the Internet to perform the lookups, so your application will require an INTERNET uses-permission tag in your manifest.
Add the following uses-permission node within the manifest node of your manifest.
<uses-permission android:name="android.permission.INTERNET" />
The reason for this is the non-existent Backend Service:
The Geocoder class requires a backend service that is not included in the core android framework. The Geocoder query methods will return an empty list if there no backend service in the platform.
First get Latitude and Longitude using Location and LocationManager class. Now try the code below for Get the city,address info
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());
}
City info is now in sb. Now convert the sb to String (using sb.toString() ).
Well, I am still stumped. So here is more code.
Before I leave my map, I call SaveLocation(myMapView,myMapController); This is what ends up calling my geocoding information.
But since getFromLocation can throw an IOException, I had to do the following to call SaveLocation
try
{
SaveLocation(myMapView,myMapController);
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
Then I have to change SaveLocation by saying it throws IOExceptions :
public void SaveLocation(MapView mv, MapController mc) throws IOException{
//I do this :
Geocoder myLocation = new Geocoder(getApplicationContext(), Locale.getDefault());
List myList = myLocation.getFromLocation(latPoint, lngPoint, 1);
//...
}
And it crashes every time.
Use this
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(lat, lng, 1);

Categories

Resources