geocoder.getFromLocationName error - java

Getting "always true" result on if (location != null || !location.equals("")) and when I search something like "sldjfuhsdhfj" it closes the app, but when I enter something like "Central Park" it works correctly.
What am I doing wrong?
Code I am using
public void onMapSearch(View view) {
EditText locationSearch = (EditText) findViewById(R.id.editText1);
String location = locationSearch.getText().toString();
List<Address> addressList = null;
if (location != null || !location.equals("")) {
Geocoder geocoder = new Geocoder(this);
try {
addressList = geocoder.getFromLocationName(location, 1);
} catch (IOException e) {
e.printStackTrace();
}
Address address = addressList.get(0);
LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());
mMap.addMarker(new MarkerOptions().position(latLng).title("Marker"));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 16));
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
// Do something after 3s
mMap.clear();
}
}, 3000);
}
}

Address address = addressList.get(0)
You gave it junk so it is returning no results. addressList is empty. You are accessing the 0 element of something that is empty. You should have seen a message in the Android Monitor window of Android Studio that pointed you to this exact line / issue.

Related

I have trouble in SearchView Google Maps

searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
String location = searchView.getQuery().toString();
//List<Address> addressList = new ArrayList<>();
List<Address> addressList = null;
if(location != null || !location.equals("")){
Geocoder geocoder = new Geocoder(MapsActivity.this);
try{
addressList = geocoder.getFromLocationName(location,1);
} catch (IOException e) {
e.printStackTrace();
}
Address address = addressList.get(0);
LatLng latLng = new LatLng(address.getLatitude(),address.getLongitude());
mMap.addMarker(new MarkerOptions().position(latLng).title(location));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng,10));
}
return false;
}
#Override
public boolean onQueryTextChange(String s) {
return false;
}
});
It's working on AVD Emulator but not working on my phone. I searching something and crash have error "
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.coffeebakeryfordriver, PID: 27228
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.get(ArrayList.java:437)
at com.example.coffeebakeryfordriver.MapsActivity$2.onQueryTextSubmit(MapsActivity.java:96)
at android.widget.SearchView.onSubmitQuery(SearchView.java:1301)
at android.widget.SearchView.access$1000(SearchView.java:101)
at android.widget.SearchView$7.onEditorAction(SearchView.java:1278)
at android.widget.TextView.onEditorAction(TextView.java:7042)
at com.android.internal.widget.EditableInputConnection.performEditorAction(EditableInputConnection.java:138)
at com.android.internal.view.IInputConnectionWrapper.executeMessage(IInputConnectionWrapper.java:357)
at com.android.internal.view.IInputConnectionWrapper$MyHandler.handleMessage(IInputConnectionWrapper.java:89)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:224)
at android.app.ActivityThread.main(ActivityThread.java:7551)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:995)
I/Process: Sending signal. PID: 27228 SIG: 9
"
use this method below in your class and call the method inside at onReadyMap() method , this work with me fine .
private void searchMethod(){
// adding on query listener for our search view.
binding.idSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
// on below line we are getting the
// location name from search view.
String location = binding.idSearchView.getQuery().toString();
// below line is to create a list of address
// where we will store the list of all address.
List<Address> addressList = null;
// checking if the entered location is null or not.
if (location != null || location.equals("")) {
// on below line we are creating and initializing a geo coder.
Geocoder geocoder = new Geocoder(MapsActivity.this);
try {
// on below line we are getting location from the
// location name and adding that location to address list.
addressList = geocoder.getFromLocationName(location, 1);
} catch (IOException e) {
e.printStackTrace();
}
// on below line we are getting the location
// from our list a first position.
Address address = addressList.get(0);
// on below line we are creating a variable for our location
// where we will add our locations latitude and longitude.
LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());
// on below line we are adding marker to that position.
mMap.addMarker(new MarkerOptions().position(latLng).title(location));
// below line is to animate camera to that position.
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 10));
}
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
return false;
}
});
}

why the city of my current location is null in android studio?

hi I made a simple app that gets current location with gps and shows the current city but when I run it, it shows latitude and longitude correctly but returns city as null
Location mLastLocation = locationResult.getLastLocation();
lat = mLastLocation.getLatitude() + "";
lon = mLastLocation.getLongitude() + "";
Geocoder gcd = new Geocoder(MLocationListener.this, Locale.getDefault());
List<Address> addresses;
try {
addresses = gcd.getFromLocation(mLastLocation.getLatitude(), mLastLocation.getLongitude(), 1);
if (addresses.size() > 0) {
// Log.d("city", addresses.get(0).getLocality());
String cityName = addresses.get(0).getLocality();
//Toast.makeText(MLocationListener.this, cityName, Toast.LENGTH_SHORT).show();
}
} catch (IOException e) {
e.printStackTrace();
}
Try this solution:
Google map = googleMap;
this.map = googleMap;
this.map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
this.map.getUiSettings().setZoomControlsEnabled(true);
this.map.getUiSettings().setCompassEnabled(true);
this.map.getUiSettings().setMyLocationButtonEnabled(true);
this.map.getUiSettings().setZoomGesturesEnabled(true);
this.map.getUiSettings().setRotateGesturesEnabled(true);
String s = "New York";
List<Address> addressList = null;
if(s!=null){
Geocoder geocoder = new Geocoder( ); //inside put "getActivity()" or "this"
try{
addressList=geocoder.getFromLocationName(s, 1);
}catch(IOException e){
e.printStackTrace();
}
Address address = addressList.get(0);
LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());
map.addMarker(new MarkerOptions().position(latLng).title(s));
map.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 10));
}
Is good to put this type of solution inside a class which implements OnMapReadyCallback, inside the method OnMapReady(GoogleMap googleMap)
Hope this can help you

Geocoder is not working in android above kitkat version

I was working with geocoder in my android app to get country name using latitude and longitude. I found that it was working good in kitkat version and below. But when i test my app in above versions it was giving null. So my question is simple that how to use geocoder above kitkat versions.
If there is any other better option instead of geocoder then please suggest me!
Thanks in advance!
I post my code for Geocoder. Follow it
//Keep this GeocodingLocation.java in a separate file.
public class GeocodingLocation {
private static final String TAG = "GeocodingLocation";
public static void getAddressFromLocation( final String locationAddress,
final Context context, final Handler handler) {
Thread thread = new Thread() {
#Override
public void run() {
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
String result = null;
String latitude = null;
String longitude = null;
try {
List<Address> addressList = geocoder.getFromLocationName(locationAddress, 1);
if (addressList != null && addressList.size() > 0) {
Log.e("GeocodingLocation --> getAddressFromLocation ==>" +
addressList.toString());
Address address = (Address) addressList.get(0);
StringBuilder sb = new StringBuilder();
latitude = String.valueOf(address.getLatitude());
longitude = String.valueOf(address.getLongitude());
Logger.infoLog("GeocodingLocation --> Lat & Lang ==>" + latitude +" "+longitude);
//sb.append(address.getLatitude()).append("\n");
//sb.append(address.getLongitude()).append("\n");
}
} catch (IOException e) {
Log.e(TAG, "Unable to connect to Geocoder", e);
} finally {
Message message = Message.obtain();
message.setTarget(handler);
if (latitude != null && longitude != null) {
message.what = 1;
Bundle bundle = new Bundle();
bundle.putString("latitude", latitude);
bundle.putString("longitude", longitude);
message.setData(bundle);
} else {
message.what = 1;
Bundle bundle = new Bundle();
result = "Address: " + locationAddress +
"\n Unable to get Latitude and Longitude for this address location.";
bundle.putString("address", result);
message.setData(bundle);
}
message.sendToTarget();
}
}
};
thread.start();
}
}
call the class from your fragment.
private void getAddressLatitudeLongitude(String branchAddress) {
Log.e("getAddressLatitudeLongitude ==>" + branchAddress);
GeocodingLocation.getAddressFromLocation(branchAddress, thisActivity, new GeocoderHandler());
}
Keep this class as inner class in same fragment
private class GeocoderHandler extends Handler {
#Override
public void handleMessage(Message message) {
switch (message.what) {
case 1:
try {
Bundle bundle = message.getData();
latitude = bundle.getString("latitude");
longitude = bundle.getString("longitude");
Log.e("CreateBranch --> GeocoderHandler ==>" + latitude + " " + longitude);
}catch (Exception e){
e.printStackTrace();
}
break;
default:
latitude = null;
longitude = null;
}
latitudeList.add(latitude);
longitudeList.add(longitude);
if(latitude==null || longitude==null){
showAlertDialog("Please enter correct address", Constants.APP_NAME);
}
Log.e("Latitude list =>" + latitudeList);
Log.e("Longitude list =>" + longitudeList);
}
}
Output will get latitude and longitude. Hope this answer helps.

Geocoder often returns null vallues in Android

I am trying to pass geocoder values from MapFragment to LocationDetailsActivity.
I get the correct values for lat and lng, but when I try to display any of the other values, most of the times I get null values instead of the city and zip (but not always), while a lot of the times I get the correct country and state (also not always).
MapFragment Code:
// Set default latitude and longitude
double latitude = 15.4825766;
double longitude = -5.0076589;
// Get latitude and longitude of the current location and a LatLng object
if (myLocation != null) {
latitude = myLocation.getLatitude();
longitude = myLocation.getLongitude();
}
mMap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {
#Override
public void onMapLongClick(LatLng arg0) {
Geocoder geocoder = new Geocoder(getActivity(), Locale.getDefault());
try {
List<Address> allAddresses = geocoder.getFromLocation(arg0.latitude, arg0.longitude, 1);
if (allAddresses.size() > 0 && allAddresses != null) {
Address address = allAddresses.get(0);
Intent intent = new Intent(getActivity(), LocationDetailsActivity.class);
intent.putExtra("latitude", arg0.latitude);
intent.putExtra("longitude", arg0.longitude);
intent.putExtra("city", allAddresses.get(0).getLocality());
intent.putExtra("zip", allAddresses.get(0).getPostalCode());
intent.putExtra("state", allAddresses.get(0).getAdminArea());
intent.putExtra("country", allAddresses.get(0).getCountryName());
startActivity(intent);
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
LocationDetailsActivity Code:
Bundle bundle = getIntent().getExtras();
double lat = bundle.getDouble("latitude");
double lng = bundle.getDouble("longitude");
String city = intent.getStringExtra("city");
String zip = intent.getStringExtra("zip");
String state = intent.getStringExtra("state");
String country = intent.getStringExtra("country");
// I display my values here
mFirstValueDisplay.setText(String.valueOf(city));
mSecondValueDisplay.setText(String.valueOf(zip));
Android's geocoding api is pretty unreliable up-to my experience, I usually make a request to the Google's geocoding webservices on Url : "https://maps.googleapis.com/maps/api/geocode"
(If you are familiar with retrofit)
#GET("/json")
void reverseGeoCode(#Query("latlng") String latlng, #Query("language") String language,
#Query("key") String key, Callback<ReverseGeoCode> callback);
latlng The latitude and longitude you want to reverse geocode.
language language of the geocoded response
key Your Api key
Go here for more info
Geocoder often got the values right, but more often than not I got null values. Based on #insomniac's advice I modified my code:
public void onMapLongClick(final LatLng arg0) {
RequestQueue queue = Volley.newRequestQueue(getActivity());
String url = "https://maps.googleapis.com/maps/api/geocode/json?latlng=" + String.valueOf(arg0.latitude) + "," + String.valueOf(arg0.longitude) + "&key=myKeyCode";
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray jObj = new JSONObject(response).getJSONArray("results").getJSONObject(0).getJSONArray("address_components");
Intent intent = new Intent(getActivity(), LocationDetailsActivity .class);
for (int i = 0; i < jObj.length(); i++) {
String componentName = new JSONObject(jObj.getString(i)).getJSONArray("types").getString(0);
if (componentName.equals("postal_code") || componentName.equals("locality")) {
intent.putExtra(componentName, new JSONObject(jObj.getString(i)).getString("short_name"));
}
}
intent.putExtra("latitude", arg0.latitude);
intent.putExtra("longitude", arg0.longitude);
startActivity(intent);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
int x = 1;
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
It still displays some areas as null. But those are smaller areas. Hope someone finds it helpful.

Android Asynctask return value in onCreate of Activity

Here in for loop i want to call Async return value. i want to call that value in snippet after title.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_full_map);
Intent i = getIntent();
lat = i.getStringArrayListExtra("L");
longi = i.getStringArrayListExtra("Longitude");
len=lat.size();
for(;j<len;j++){
LatLng location = new LatLng(Double.valueOf(lat.get(j)).doubleValue(),
Double.valueOf(longi.get(j)).doubleValue()) ;
new ReverseGeocodingTask(getBaseContext()).execute(location);
googlemap.addMarker(new MarkerOptions()
.title(plat.get(j).toString())
.snippet(snippet)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_CYAN))
.position(location)
);
}
}
Here Below is my AsyncTask code where i am returning the values. please some take a look and explain me my silly mistake....
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;
try {
addresses = geocoder.getFromLocation(latitude, longitude,1);
} catch (IOException e) {
e.printStackTrace();
}
if(addresses != null && addresses.size() > 0 ){
Address address = addresses.get(0);
addressText = String.format("%s, %s, %s",
address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
address.getLocality(),
address.getCountryName());
}
return addressText;
}
#Override
protected void onPostExecute(String addressResult) {
// Setting the title for the marker.
// This will be displayed on taping the marker
snippet = addressResult;
super.onPostExecute(snippet);
//Toast.makeText(Show_full_map.this,addressText,Toast.LENGTH_LONG).show();
}
}
I guess you want snippet immediately after calling execute. This is not how AsyncTask works. You can pass location in constructor of AsyncTask and access it from onPostExecute().
Just move the following code from your for loop to onPostExecute():
#Override
protected void onPostExecute(String snippet) {
super.onPostExecute(snippet);
googlemap.addMarker(new MarkerOptions()
.title(plat.get(j).toString())
.snippet(snippet)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_CYAN))
.position(location)
);
}

Categories

Resources