App Crashes when entering invalid or null location using geocoder - android

I have been working on google maps and want the user can access location using geocoding, although it is working but the problem arises when the user enters invalid location or null location in edit text, my app gets crashed.
This is my code: (on search button click)
public void onSearch(View view) {
EditText addressSearch = (EditText) findViewById(R.id.edtSearchAddress);
String location = addressSearch.getText().toString();
List<Address> addressList = null;
if (location != null || !location.equals("")) {
addressSearch.setText("");
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
try {
addressList= geocoder.getFromLocationName(location, 7);
} catch (IOException e) {
e.printStackTrace();
}
// location exists
Address address = addressList.get(0);
LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());
map.addMarker(new MarkerOptions().position(latLng).title("Find Pro"));
map.animateCamera(CameraUpdateFactory.newLatLng(latLng));
} else {
addressSearch.setText("Location does not exist");
}
}
Your kind support will be appreciated.

According to documentation the call of geocoder.getFromLocationName can throw IllegalArgumentException or return empty list. Both cases will crash your app. My bet the list is empty.
So guard your code:
if (addressList.size() > 0) {
Address address = addressList.get(0);
LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());
map.addMarker(new MarkerOptions().position(latLng).title("Find Pro"));
map.animateCamera(CameraUpdateFactory.newLatLng(latLng));
}

when you pass null value that time addressList return 0 value so please set IF condition before get value from addressList.
if (addressList.size() > 0) {
Address address = addressList.get(0);
}

Related

How to show the progress dialog when call Geocoder methods

I am trying to get latitude longitude of list of address using this method
public LatLng getLocationFromAddress(String strAddress){
Geocoder coder = new Geocoder(getActivity());
List<Address> address;
LatLng p1 = null;
try {
// May throw an IOException
address = coder.getFromLocationName(strAddress, 5);
if (address == null || address.size() == 0) {
return null;
}
Address location = address.get(0);
p1 = new LatLng(location.getLatitude(), location.getLongitude() );
} catch (IOException ex) {
ex.printStackTrace();
}
return p1;
}
and I called this method inside the for loop, I want to show progress dialog till all latitude longitude points are receiving but my progress dialog not showing. I assume this may because of different threads can anyone help with this issue?
Progress bar will not show up because the time taken to receive latitude and longitude takes fraction of milli seconds and will give no time to load the progress bar.

How to get Latitude Longitude from more than 500 addresses?

I have more than 700 addresses in database.
I want to plot them region wise.
I have implement this code :
public LatLng getSingleLocationFromAddress(String strAddress)
{
Geocoder coder = new Geocoder(this, Locale.getDefault());
List<Address> address = null;
Address location = null;
GeoPoint p1 = null;
LatLng temp = null;//new LatLng(26.0000, 121.0000);
String strAddresNew = strAddress.replace(",", " ");
try
{
address = coder.getFromLocationName(strAddresNew, 1);
if (!address.isEmpty())
{
location = address.get(0);
location.getLatitude();
location.getLongitude();
temp = new LatLng(location.getLatitude(), location.getLongitude());
Log.d("Latlng : ", temp + "");
} else
{
arrTemp.add(strAddress);
System.out.println(arrTemp);
}
} catch (IOException e)
{
Toast.makeText(mContext, e.toString(), Toast.LENGTH_LONG).show();
e.printStackTrace();
} catch (Exception e)
{
e.printStackTrace();
}
return temp;
}
But the problem is when I call this method in loop like this:
Marker TP1 = googleMap.addMarker(new MarkerOptions().position(getSingleLocationFromAddress(fullAddress)));
The line coder.getFromLocationName(strAddresNew, 1); returns null for some addresses, for example if I have an ArrayList of 7 addresses then I get only 4-5 LatLong values.
Use below lines of code...It can be helpful for you
Declare these variables above yours Oncreate or OncreatView
List<Address> From_geocode = null;
private double sLat, sLong;
private Geocoder geocoder;
Than inside yours oncreate or oncreateVIew use these lines of code
geocoder = new Geocoder(getActivity());
try {
From_geocode = geocoder.getFromLocationName("PUT THE ADDRESS HERE", 1);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if (From_geocode.size() > 0) {
System.out.println("2");
From_geocode.get(0).getLatitude(); // getting
// latitude
From_geocode.get(0).getLongitude();
sLat = From_geocode.get(0).getLatitude();
sLong = From_geocode.get(0).getLongitude();
System.out.println("LATITUTE====="+sLat+" LONGITUTE====="+sLong);
}
And provide the entry inside the manifest file
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
Although the google database is extensive it is possible that some of the addresses that you have supplied could not be geocoded. Hence you will not get a lat/lon for those addresses. You could probably check the status of the response.
As mentioned in the link below
https://developers.google.com/maps/documentation/geocoding/#StatusCodes
The "status" field within the Geocoding response object contains the status of the request, and may contain debugging information to help you track down why geocoding is not working. The "status" field may contain the following values:
"OK" indicates that no errors occurred; the address was successfully parsed and at least one geocode was returned.
"ZERO_RESULTS" indicates that the geocode was successful but returned no results. This may occur if the geocoder was passed a non-existent address.

implementing the requestlocationchange in google maps

In my application, I have google maps and I'm currently showing my location using gps but i have a user input field where user can give their location, based on the user input my location should change to user location
You can use a CameraUpdate to change the position
LatLng latLng = user's position
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLng(latLng)
map.moveCamera(cameraUpdate);
if the user inputs an address and not the coordinates (which is very likely) you can use a geocoder to get the coordinates from the address
Geocoder coder = new Geocoder(this);
List<Address> address;
try {
address = coder.getFromLocationName(strAddress,5);
if (address == null) {
return null;
}
Address location = address.get(0);
location.getLatitude();
location.getLongitude();
}

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: App crashes while entering invalid location

In my app, I have to find whether a given location comes under a specified area. I am taking Connaught Place, New Delhi as center point. and I got the addresses which come under area of 200 miles from center point. But, if I enter any invalid location, like "abcdfdfkc", the app crashes, because it is trying to find coordinates of this location and I want to avoid this.
Below I am posting the code:
public static boolean isServicedLocation(Context _ctx, String strAddress){
boolean isServicedLocation = false;
Address sourceAddress = getAddress(_ctx, "Connaught Place, New Delhi, India");
Location sourceLocation = new Location("");
sourceLocation.setLatitude(sourceAddress.getLatitude());
sourceLocation.setLongitude(sourceAddress.getLongitude());
Address targetAddress = getAddress(_ctx, strAddress);
Location targetLocation = new Location("");
if (targetLocation != null) {
targetLocation.setLatitude(targetAddress.getLatitude());
targetLocation.setLongitude(targetAddress.getLongitude());
float distance = Math.abs(sourceLocation.distanceTo(targetLocation));
double distanceMiles = distance/1609.34;
isServicedLocation = distanceMiles <= 200;
//Toast.makeText(_ctx, "Distance "+distanceMiles, Toast.LENGTH_LONG).show();
}
return isServicedLocation;
}
getAddress method:
public static Address getAddress(Context _ctx, String addressStr) {
Geocoder geoCoder = new Geocoder(_ctx, Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocationName(addressStr,
1);
if (addresses.size() != 0) {
return addresses.get(0);
}
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
It's because when you don't find an address from the GeoCoder (ie, if addresses.size() == 0), you return null.
Then, regardless of that, you dereference the value, which is what's crashing your app.
Address targetAddress = getAddress(_ctx, strAddress);
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
:
if (targetLocation != null) {
targetLocation.setLatitude(targetAddress.getLatitude());
^^^^^^^^^^^^^
You should probably also be checking targetAddress for null to avoid this (either in addition to (likely), or instead of (less likely), the check of targetLocation).
So I'd be looking at changing:
if (targetLocation != null) {
into:
if ((targetLocation != null) && (targetAddress != null)) {
That way, an invalid address automatically becomes an unserviced location.

Categories

Resources