I have trouble in SearchView Google Maps - java

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;
}
});
}

Related

How mapbox navigation draw(Polyline) user location changed coordinates on Map?

private static class LocationChangeListeningActivityLocationCallback
implements LocationEngineCallback<LocationEngineResult> {
private final WeakReference<MapMatchingActivity> activityWeakReference;
LocationChangeListeningActivityLocationCallback(MapMatchingActivity activity) {
this.activityWeakReference = new WeakReference<>(activity);
}
#Override
public void onSuccess(LocationEngineResult result) {
MapMatchingActivity activity = activityWeakReference.get();
if (activity != null) {
Location location = result.getLastLocation();
Feature feature = Feature.fromGeometry(Point.fromLngLat(result.getLastLocation().getLongitude(),result.getLastLocation().getLatitude()));
if (location == null) {
return;
}
Log.e("Coords", String.valueOf(result.getLastLocation().getLatitude() +" " + result.getLastLocation().getLongitude()));
String[] latlong = (result.getLastLocation().getLatitude() +"," + result.getLastLocation().getLongitude()).split(",");
double latitude = Double.parseDouble(latlong[0]);
double longitude = Double.parseDouble(latlong[1]);
latLngList.add(new LatLng(longitude,latitude));
// activity.drawMarker();
}
}
#Override
public void onFailure(#NonNull Exception exception) {
MapMatchingActivity activity = activityWeakReference.get();
if (activity != null) {
Toast.makeText(activity, exception.getLocalizedMessage(),
Toast.LENGTH_SHORT).show();
}
}
}
The above code where I am getting user location coordinates, I got to know that MapBox updated SDK, and PolylineOptions is now Deprecated, I have drawn lines using LineOptions but still have No idea how to update based on user location Please check below code.
private void getDirection(List<LatLng> coordinates,LatLng latLng){
List<LatLng> latLngs = new ArrayList<>();
latLngs.add(new LatLng(21.23504447 ,72.81109308));
latLngs.add(new LatLng( 21.23471482921968, 72.81101793050766));
latLngs.add(new LatLng(21.23425981047001, 72.81080335378647));
LineOptions lineOptions = new LineOptions()
.withLatLngs(latLngs)
.withLineColor(ColorUtils.colorToRgbaString(Color.BLACK))
.withLineWidth(5.0f);
lineManager.create(lineOptions);
}

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

How to set text to Google Maps current location from another class

I created a seperate activity to create a Google Map and set a marker on the users current location. In another fragment class, I'd like to set the text of a text view to the location from the map activity.
CheckInFragment
mLocation = (TextView) v.findViewById(R.id.checkin_location_text);
mLocation.setText();
MapsActivity
private void handleNewLocation(Location location){
//SET THESE TWO VARIABLES TO THE TEXT vv
double currentLatitude = location.getLatitude();
double currentLongitude = location.getLongitude();
LatLng latLng = new LatLng(currentLatitude, currentLongitude);
MarkerOptions options = new MarkerOptions()
.position(latLng)
.title("Check In Location");
mMap.addMarker(options);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
float zoomLevel = 16.0f;
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoomLevel));
}
You can try below code to get the string value of location:
Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
try {
List<Address> addressList = geocoder.getFromLocation(location.getLatitude(),
location.getLongitude(), 1);
String fullAddress = "";
if (addressList != null && addressList.size() > 0) {
if (addressList.get(0).getAddressLine(0) != null) {
fullAddress += addressList.get(0).getAddressLine(0) + " ";
}
if (addressList.get(0).getSubAdminArea() != null) {
fullAddress += addressList.get(0).getSubAdminArea() + " ";
}
} else {
Log.d("Address:", "Couldn't find Address");
}
} catch (IOException e) {
e.printStackTrace();
}
Then you can pass the fullAddress string value in a bundle when calling the your fragment class, something like:
YourFragment fragment = new YourFragment();
Bundle args = new Bundle();
args.putString("location_string", fullAddress);
fragment.setArguments(args);
Finally in onCreate method of your Fragment class fetch the string value as below:
if (getArguments() != null)
{
_location = getArguments().getString("location_string");
}
Hope this helps!!!

geocoder.getFromLocationName error

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.

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