Variable is initialized but appears to be null in onClick method - java

public class PickUpFragment extends SherlockFragment implements OnMarkerDragListener, OnCameraChangeListener
{
View rootView;
private SupportMapFragment fragment;
private GoogleMap map;
private MySupportMapFragment itsMySupportMapFragment;
RelativeLayout progress_rl;
RelativeLayout map_rl;
Button button;
public LatLng latlng;
TextView tv;
public String address = "";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_pickup, container, false);
progress_rl= (RelativeLayout)rootView.findViewById(R.id.progress);
map_rl = (RelativeLayout)rootView.findViewById(R.id.map_container);
//button.setOnClickListener(pickup);
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
itsMySupportMapFragment = new MySupportMapFragment();
MapViewCreatedListener mapViewCreatedListener = new MapViewCreatedListener() {
#Override
public void onMapCreated() {
initPlacesGoogleMapCtrl();
}
};
itsMySupportMapFragment.itsMapViewCreatedListener = mapViewCreatedListener;
FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.map, itsMySupportMapFragment);
transaction.addToBackStack(null);
transaction.commit();
}
Marker marker;
Location loc;
public void initPlacesGoogleMapCtrl() {
// Map ready, get it.
map = itsMySupportMapFragment.getMap();
// Do what you want...
map.setOnCameraChangeListener(this);
map.moveCamera(CameraUpdateFactory.zoomTo(15));
// Acquire a reference to the system Location Manager
LocationManager locationManager = (LocationManager) this.getSherlockActivity().getSystemService(Context.LOCATION_SERVICE);
// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider
latlng = new LatLng(location.getLatitude(),location.getLongitude());
if(loc == null)
{
loc = location;
map.moveCamera(CameraUpdateFactory.newLatLng(latlng));
//marker = map.addMarker(new MarkerOptions().position(new LatLng(location.getLatitude(),location.getLongitude())).draggable(true));
try {
tv = (TextView) rootView.findViewById(R.id.map_address);
Geocoder geo = new Geocoder(PickUpFragment.this.getSherlockActivity().getApplicationContext(), Locale.getDefault());
List<Address> addresses = geo.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
if (addresses.isEmpty()) {
tv.setText("Waiting for Location");
}
else {
if (addresses.size() > 0) {
String addr = "";
if(addresses.get(0).getFeatureName() != null || addresses.get(0).getFeatureName().equals("null"))
{
addr += addresses.get(0).getFeatureName();
}
if(addresses.get(0).getThoroughfare() != null || addresses.get(0).getThoroughfare().equals("null") && !addresses.get(0).getThoroughfare().equals(addresses.get(0).getFeatureName()))
{
addr += " " + addresses.get(0).getThoroughfare();
}
if(addresses.get(0).getLocality() != null || addresses.get(0).getLocality().equals("null"))
{
addr += ", " + addresses.get(0).getLocality();
}
address = addr + ", " + addresses.get(0).getAdminArea();
tv.setText(address);
//Toast.makeText(getApplicationContext(), "Address:- " + addresses.get(0).getFeatureName() + addresses.get(0).getAdminArea() + addresses.get(0).getLocality(), Toast.LENGTH_LONG).show();
}
}
}
catch (Exception e) {
e.printStackTrace(); // getFromLocation() may sometimes fail
}
}
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
}
public void pickup(View v, Activity act)
{
Sync sync = new Sync();
String ad = tv.getText().toString();
sync.makeBooking(latlng, ad, getActivity());
RelativeLayout progress_rl = (RelativeLayout)act.findViewById(R.id.progress);
progress_rl.setVisibility(getView().VISIBLE);
RelativeLayout map_rl = (RelativeLayout)act.findViewById(R.id.map_container);
map_rl.setVisibility(getView().GONE);
ProgressBar spinner = (ProgressBar) progress_rl.findViewById(R.id.progress_bar);
spinner.getIndeterminateDrawable().setColorFilter(0xFFFF0000, android.graphics.PorterDuff.Mode.MULTIPLY);
}
#Override
public void onDetach() {
super.onDetach();
try {
Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager");
childFragmentManager.setAccessible(true);
childFragmentManager.set(this, null);
} catch (NoSuchFieldException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
#Override
public void onMarkerDrag(Marker arg0) {
// TODO Auto-generated method stub
}
#Override
public void onMarkerDragEnd(Marker arg0) {
}
#Override
public void onMarkerDragStart(Marker arg0) {
// TODO Auto-generated method stub
}
#Override
public void onCameraChange(CameraPosition arg0) {
try
{
latlng = arg0.target;
tv = (TextView) rootView.findViewById(R.id.map_address);
Async async = new Async();
async.execute();
}
catch(Exception e)
{
}
}
private class Async extends AsyncTask<String,String,String>
{
#Override
protected String doInBackground(String... arg0) {
try
{
Geocoder geo = new Geocoder(PickUpFragment.this.getSherlockActivity().getApplicationContext(), Locale.getDefault());
List<Address> addresses = geo.getFromLocation(latlng.latitude, latlng.longitude, 1);
if (addresses.isEmpty()) {
}
else {
if (addresses.size() > 0) {
String addr = "";
if(addresses.get(0).getFeatureName() != null && !addresses.get(0).getFeatureName().equals("null"))
{
addr += addresses.get(0).getFeatureName();
}
if(addresses.get(0).getThoroughfare() != null && !addresses.get(0).getThoroughfare().equals("null") && !addresses.get(0).getThoroughfare().equals(addresses.get(0).getFeatureName()))
{
addr += " " + addresses.get(0).getThoroughfare();
}
if(addresses.get(0).getLocality() != null && !addresses.get(0).getLocality().equals("null"))
{
addr += ", " + addresses.get(0).getLocality();
}
address = addr + ", " + addresses.get(0).getAdminArea();
//Toast.makeText(getApplicationContext(), "Address:- " + addresses.get(0).getFeatureName() + addresses.get(0).getAdminArea() + addresses.get(0).getLocality(), Toast.LENGTH_LONG).show();
}
}
}
catch(IOException e)
{
}
return null;
}
#Override
protected void onPreExecute()
{
tv.setText("Waiting for Location");
}
#Override
protected void onPostExecute(String result)
{
tv.setText(address);
}
}
}
The TextView tv is initialized the method initPlacesGoogleMapCtrl(). When I debug and step through line by line I can see that it was the correct value.
But when I try to use this value in pickup() it's null even though it was initialized earlier.
rootView and all the other class variables that are set throughout the running of the app are all null in the pickup method.
Any idea why it would be initialized and then suddenly it's null?

Related

App getting hang and crash while loading thousands of marker, Please help to get this fix

After updating google map to 18.0.2, map screen getting hanged and crash with ANR while loading thousands of marker cluster on map.
Basically, What's happening is, an api is get call every time when map is scrolled by the user. Then in api response, I'm getting list of restaurants with all the details like lat/lng points, name, title etc. and then call goes to addItem()method which updates the clusterMapList with the restaurant details in a thread and then clusterManager.addItems() is get called on the main thread to add the markers on google map. Then pre setup cluster manager shows the markers and the markers used are the custom markers (.png) from drawables.
Here's the code snippet
private void addItem() {
try {
if (thread != null) {
if (thread.isAlive()) {
thread.interrupt();
}
clusterMapList.clear();
clusterManager.clearItems();
}
if (restaurantListMap != null) {
thread = new Thread(new Runnable() {
#Override
public void run() {
for (RestaurantDatum obj: restaurantListMap) {
clusterMapList.add(new clusterMapList(
Double.parseDouble(obj.getLatitude()), Double.parseDouble(obj.getLongitude()), obj.getRestaurantName(), obj.getCity() + ", " + obj.getState(), obj.getCategory(), obj.getRestaurantId(), obj.getImageUrl()
));
} //for each
runOnUiThread(new Runnable() {
#Override
public void run() {
clusterManager.addItems(clusterMapList);
clusterManager.cluster();
}
});
}
});
thread.start();
} //if
} catch (Exception e) {
e.printStackTrace();
}
} //addItem
private void setUpClusterManager(GoogleMap googleMap) {
clusterManager = new ClusterManager < > (this, googleMap);
clusterManager.setRenderer(new DefaultClusterRenderer < clusterMapList > (this, googleMap, clusterManager) {
#Override
protected void onBeforeClusterItemRendered(#NonNull clusterMapList item, #NonNull MarkerOptions markerOptions) {
BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory.fromResource(R.drawable.map_marker_gf_small_1);
markerOptions.icon(bitmapDescriptor);
super.onBeforeClusterItemRendered(item, markerOptions);
}
#Override
protected void onClusterItemRendered(#NonNull com.glutendudeapp.ui.letseat.clusterMapList clusterItem, #NonNull Marker marker) {
if (clusterItem.getCategory().equalsIgnoreCase("yes")) {
try {
marker.setIcon(bitmapDescriptorGF);
} catch (Exception e) {
e.printStackTrace();
}
} else {
try {
marker.setIcon(bitmapDescriptorCC);
} catch (Exception e) {
e.printStackTrace();
}
}
marker.setTag(clusterItem.getImageUrl() + "");
super.onClusterItemRendered(clusterItem, marker);
} //onClusterItemRendered
#Override
protected void onClusterRendered(#NonNull Cluster < clusterMapList > cluster, #NonNull Marker marker) {
super.onClusterRendered(cluster, marker);
} //onClusterRendered
});
clusterManager.getMarkerCollection().setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
#Nullable
#Override
public View getInfoContents(#NonNull Marker marker) {
return null;
}
#Nullable
#Override
public View getInfoWindow(#NonNull Marker marker) {
windlowInfoClicked = true;
View v = getLayoutInflater().inflate(R.layout.map_custom_infowindow, null);
ImageView img = (ImageView) v.findViewById(R.id.imgRest);
ProgressBar bar = (ProgressBar) v.findViewById(R.id.bar);
TextView tvTitle = (TextView) v.findViewById(R.id.title_map);
TextView tvSnippet = (TextView) v.findViewById(R.id.snippet_map);
tvTitle.setText(marker.getTitle());
String snip = marker.getSnippet();
tvSnippet.setText(snip);
try {
Address addr = Utility.getAddress(LetsEatActivity.this, marker.getPosition().latitude, marker.getPosition().longitude);
String addrr = addr.getAddressLine(0);
tvSnippet.setText(addrr);
} catch (Exception e) {
e.printStackTrace();
}
Picasso.with(LetsEatActivity.this).load(String.valueOf(marker.getTag()))
.placeholder(R.drawable.ic_7_day_trial)
.into(img, new com.squareup.picasso.Callback() {
#Override
public void onSuccess() {
try {
if (marker != null && marker.isInfoWindowShown()) {
marker.hideInfoWindow();
marker.showInfoWindow();
}
} catch (Exception e) {
e.printStackTrace();
}
} //onSuccess
#Override
public void onError() {
}
});
return v;
} //getInfoWindow
});
clusterManager.setOnClusterItemInfoWindowClickListener(new ClusterManager.OnClusterItemInfoWindowClickListener < clusterMapList > () {
#Override
public void onClusterItemInfoWindowClick(clusterMapList item) {
Intent In = new Intent(LetsEatActivity.this, ActivityRestaurantDetails.class);
restaurandId = String.valueOf(item.getRestaurantId());
In.putExtra("restaurantId", restaurandId);
Log.e("infoWindow", restaurandId);
if (currentLocation != null) {
In.putExtra("CURRENT_LATITUDE", String.valueOf(currentLocation.getLatitude()));
In.putExtra("CURRENT_LONGITUDE", String.valueOf(currentLocation.getLongitude()));
} else {
In.putExtra("CURRENT_LATITUDE", "");
In.putExtra("CURRENT_LONGITUDE", "");
}
startActivity(In);
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
}
});
addItem();
} //setUpClusterManager
Here below is the drive link of the screen recording of the app, kindly please check.
https://drive.google.com/file/d/1CnWvCyWi4JD6h5NhvJJwmad6zZahH_uM/view?usp=sharing

Already managing a GoogleApiClient with id 0 error despite implementing onPause()

When clicked on a Cardview, my application will display a start an activity which will display nearby places in a Recycler view. But whenever I clicked on the cardview I'm having the error shown below. Miraculously when I comment out nearByPlace("restaurant") in NearbyActivity.java the program does not crash. So is it possible because the nearByPlace("restaurant") is also using the same id and how do i fix it
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.android.sunshine/com.example.android.sunshine.MainActivity}: java.lang.IllegalStateException: Already managing a GoogleApiClient with id 0
Error Logcat
ItemOneFragment.Java
private void init() {
mGeoDataClient = Places.getGeoDataClient(getActivity(), null);
// Construct a PlaceDetectionClient.
mPlaceDetectionClient = Places.getPlaceDetectionClient(getActivity(), null);
mGoogleApiClient = new GoogleApiClient
.Builder(getActivity())
.addApi(Places.GEO_DATA_API)
.addApi(Places.PLACE_DETECTION_API)
.enableAutoManage(getActivity(), 0, this)
.build();
SessionData.setSessionId("0");
mSearchText.setOnItemClickListener(mAutocompleteClickListener);
placeAutocompleteAdapter = new PlaceAutocompleteAdapter(getActivity(), mGeoDataClient, LAT_LNG_BOUNDS, null);
mSearchText.setAdapter(placeAutocompleteAdapter);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
cardShopMall = (CardView) getView().findViewById(R.id.textViewShopMall);
cardShopMall.setOnClickListener(cardShopMallOnClickListener);
if (isServicesOK()) {
getLocationPermission();
}
if (mLocationPermissionsGranted) {
getDeviceLocation();
init();
}
}
CardView.OnClickListener cardShopMallOnClickListener = new CardView.OnClickListener(){
#Override
public void onClick(View view) {
String type = "shopping_mall";
Intent i = new Intent(getContext(),NearbyActivity.class);
i.putExtra("type",type);
i.putExtra("latitude",latitude);
i.putExtra("longitude",longitude);
startActivity(i);
}
};
NearbyActivity.Java
IGoogleAPIService mServiceNear;
private GoogleApiClient mGoogleApiClient;
public NearbyActivity() {
Retrofit retrofit1 = RetrofitClient2.getClient("https://maps.googleapis.com/");
mServiceNear = retrofit1.create(IGoogleAPIService.class);
}
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mGoogleApiClient = new GoogleApiClient
.Builder(this)
.addApi(Places.GEO_DATA_API)
.addApi(Places.PLACE_DETECTION_API)
.enableAutoManage(this, 2 ,this)
.build();
Intent intent = getIntent();
String type = intent.getExtras().getString("type");
latitude = intent.getExtras().getDouble("latitude");
longitude = intent.getExtras().getDouble("longitude");
try {
nearByPlace("restaurant");
} catch (Exception e) {
e.printStackTrace();
}
}
private void nearByPlace(final String type) {
String url = getUrl(latitude,longitude,type);
Log.d(TAG,"underURL# nearByPlace : " + url);
mServiceNear.getNearByPlaces(url)
.enqueue(new Callback<MyPlaces>() {
#Override
public void onResponse(Call<MyPlaces> call, retrofit2.Response<MyPlaces> response) {
try {
if (response.isSuccessful()){
Log.d(TAG,"responnse : ok");
try {
if (response.body() != null){
for (int i=0;i<response.body().getResults().length;i++){
Results googlePlace = response.body().getResults()[i];
String placeName = googlePlace.getName();
String vicinity = googlePlace.getVicinity();
Log.d(TAG,"nearByPlaces: " + placeName);
ListItem item = new ListItem(
googlePlace.getName(),
googlePlace.getVicinity()
);
listItems.add(item);
}
}else {
Toast.makeText(getApplicationContext(),"No Nearby " + type,Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
}
adapter = new MyAdapter(listItems,NearbyActivity.this);
recyclerView.setAdapter(adapter);
}
}catch (Exception e){
e.getMessage();
}
}
#Override
public void onFailure(Call<MyPlaces> call, Throwable t) {
}
});
}
private String getUrl(double latitude, double longitude, String restaurant) {
StringBuilder googlePlacesUrl = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
googlePlacesUrl.append("location="+latitude+","+longitude);
googlePlacesUrl.append("&radius="+5000);
googlePlacesUrl.append("&type="+restaurant);
googlePlacesUrl.append("&sensor=true");
googlePlacesUrl.append("&key="+getResources().getString(R.string.GoogleAPiKey));
Log.d(TAG,"getURL : " + googlePlacesUrl.toString());
return googlePlacesUrl.toString();
}
#Override
protected void onPause() {
super.onPause();
if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
mGoogleApiClient.stopAutoManage(this);
mGoogleApiClient.disconnect();
}
}
Yes you have correctly implemented onPause for your Activity but not for your Fragment.
In your init method inside your Fragment you create a new GoogleApiClient. This differs from the one in your Activity, in which - as mentioned before - you correctly implemented onPause.
Therefore the solution to your issue should be implementing onPause for your Fragment.
I hope this will resolve your issue

error: method getMapAsync in class SupportMapFragment cannot be applied to given types;

I am getting this error
error: method getMapAsync in class SupportMapFragment cannot be
applied to given types; required: OnMapReadyCallback found: no
arguments reason: actual and formal argument lists differ in length
error: cannot access zzbgl class file for
com.google.android.gms.internal.zzbgl not found
in MapDirectionDisplayActivity.java file
This is my code
private void getLastActivityInfo()
{
lastActivityData = getIntent().getExtras();
}
private void setUpMapIfNeeded() {
if (mapView == null)
{
mapView = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
if (mapView != null)
{
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(lastActivityData.getDouble("point_one_lat")
, lastActivityData.getDouble("point_one_lon")), 15);
mapView.animateCamera(cameraUpdate);
}
}
new DirectionLoadingThread().execute();
}
#Override
public void onBackPressed() {
finish();
super.onBackPressed();
}
#Override
protected void onResume() {
try {
if(gpsTracker!=null)
gpsTracker.loctionUpdate();
} catch (Exception e) {
}
super.onResume();
}
#Override
public void finish() {
try {
if(gpsTracker!=null)
{
gpsTracker.stopUsingGPS();
gpsTracker.stopSelf();
}
} catch (Exception e) {
}
super.finish();
}
public class MyLocationListener implements LocationListener
{
Context context;
MyLocationListener(Context context)
{
this.context=context;
}
#Override
public void onProviderDisabled(String provider)
{
Toast.makeText(context,"Gps Disabled",Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderEnabled(String provider)
{
Toast.makeText(context,"Gps Enabled",Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
#Override
public void onLocationChanged(Location location)
{
double lat = location.getLatitude();
double lng= location.getLongitude();
}
}
private class DirectionLoadingThread extends AsyncTask<Void, Void, JSONArray>
{
#Override
protected JSONArray doInBackground(Void... arg0) {
String apiUrl ="http://maps.googleapis.com/maps/api/directions/json?origin="+lastActivityData.getDouble("point_one_lat")+","+lastActivityData.getDouble("point_one_lon")
+"&destination="+lastActivityData.getDouble("point_two_lat")
+","+lastActivityData.getDouble("point_two_lon")+"&sensor=false";
String result;
try {
result = CustomHttpClient.executeGet(apiUrl);
if(result!=null)
{
return new JSONObject(result).getJSONArray("routes").getJSONObject(0).getJSONArray("legs").getJSONObject(0).getJSONArray("steps");
}
}catch (Exception e) {
}
return null;
}
#Override
protected void onPostExecute(JSONArray resultArray) {
if (mapView != null)
{
mapView.addMarker(new MarkerOptions()
.position(new LatLng(lastActivityData.getDouble("point_one_lat"), lastActivityData.getDouble("point_one_lon")))
.title(lastActivityData.getString("point_location_one_title")));
LatLng lastLonLat = new LatLng(lastActivityData.getDouble("point_one_lat"), lastActivityData.getDouble("point_one_lon"));
if(resultArray!=null)
{
LatLng newLonLat = null ;
for (int i = 0; i < resultArray.length(); i++) {
try {
newLonLat = new LatLng(resultArray.getJSONObject(i).getJSONObject("end_location").getDouble("lat")
, resultArray.getJSONObject(i).getJSONObject("end_location").getDouble("lng"));
mapView.addPolyline(new PolylineOptions().add(lastLonLat
,newLonLat)
.width(3)
.color(Color.BLUE));
} catch (JSONException e) {
}
lastLonLat = newLonLat;
}
}
mapView.addMarker(new MarkerOptions()
.position(new LatLng(lastActivityData.getDouble("point_two_lat"), lastActivityData.getDouble("point_two_lon")))
.title(lastActivityData.getString("point_location_two_title")));
}
super.onPostExecute(resultArray);
}
}

How can I send current location from one activity to another?

I am using map to get current location and now I want to send my current location to another activity which has form to input all the data.
I am confused about which variables and methods I should use to send the location data.
ChooseFromMapActivity
This is the activity where I am getting my current location. And now on Click of useLocation layout I want to send this location to the edit text of another activity i.e GoSendActivity.
public class ChooseFromMapActivity extends AppCompatActivity implements
LocationListener, GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private LocationRequest mLocationRequest;
GoogleMap mGoogleMap;
private GoogleApiClient mGoogleApiClient;
boolean mUpdatesRequested = false;
private LatLng center;
private LinearLayout markerLayout;
private Geocoder geocoder;
private List<Address> addresses;
private TextView Address;
double latitude;
double longitude;
private GPSTracker gps;
private LatLng curentpoint;
private LinearLayout useLocation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_choose_from_map);
Address = (TextView) findViewById(R.id.textShowAddress);
markerLayout = (LinearLayout) findViewById(R.id.locationMarker);
useLocation = (LinearLayout)findViewById(R.id.LinearUseLoc);
int status = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(getBaseContext());
if (status != ConnectionResult.SUCCESS) { // Google Play Services are
// not available
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this,
requestCode);
dialog.show();
} else { // Google Play Services are available
// Getting reference to the SupportMapFragment
// Create a new global location parameters object
mLocationRequest = LocationRequest.create();
/*
* Set the update interval
*/
mLocationRequest.setInterval(GData.UPDATE_INTERVAL_IN_MILLISECONDS);
// Use high accuracy
mLocationRequest
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
// Set the interval ceiling to one minute
mLocationRequest
.setFastestInterval(GData.FAST_INTERVAL_CEILING_IN_MILLISECONDS);
// Note that location updates are off until the user turns them on
mUpdatesRequested = false;
/*
* Create a new location client, using the enclosing class to handle
* callbacks.
*/
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API).addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
mGoogleApiClient.connect();
}
useLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
private void stupMap() {
try {
mGoogleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
// Enabling MyLocation in Google Map
mGoogleMap.setMyLocationEnabled(true);
mGoogleMap.getUiSettings().setZoomControlsEnabled(true);
mGoogleMap.getUiSettings().setMyLocationButtonEnabled(true);
mGoogleMap.getUiSettings().setCompassEnabled(true);
mGoogleMap.getUiSettings().setRotateGesturesEnabled(true);
mGoogleMap.getUiSettings().setZoomGesturesEnabled(true);
gps = new GPSTracker(this);
gps.canGetLocation();
latitude = gps.getLatitude();
longitude = gps.getLongitude();
curentpoint = new LatLng(latitude, longitude);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(curentpoint).zoom(19f).tilt(70).build();
mGoogleMap.setMyLocationEnabled(true);
mGoogleMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
// Clears all the existing markers
mGoogleMap.clear();
mGoogleMap.setOnCameraChangeListener(new OnCameraChangeListener() {
#Override
public void onCameraChange(CameraPosition arg0) {
// TODO Auto-generated method stub
center = mGoogleMap.getCameraPosition().target;
mGoogleMap.clear();
markerLayout.setVisibility(View.VISIBLE);
try {
new GetLocationAsync(center.latitude, center.longitude)
.execute();
} catch (Exception e) {
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
#Override
public void onConnectionFailed(ConnectionResult arg0) {
// TODO Auto-generated method stub
}
#Override
public void onConnected(Bundle arg0) {
// TODO Auto-generated method stub
stupMap();
}
private class GetLocationAsync extends AsyncTask<String, Void, String> {
// boolean duplicateResponse;
double x, y;
StringBuilder str;
public GetLocationAsync(double latitude, double longitude) {
// TODO Auto-generated constructor stub
x = latitude;
y = longitude;
}
#Override
protected String doInBackground(String... params) {
try {
geocoder = new Geocoder(ChooseFromMapActivity.this, Locale.ENGLISH);
addresses = geocoder.getFromLocation(x, y, 1);
str = new StringBuilder();
if (Geocoder.isPresent()) {
if ((addresses != null) && (addresses.size() > 0)) {
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 + "");
}
} else {
}
} catch (IOException e) {
Log.e("tag", e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(String result) {
try {
Address.setText(addresses.get(0).getAddressLine(0)
+ addresses.get(0).getAddressLine(1) + " ");
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
#Override
public void onConnectionSuspended(int arg0) {
// TODO Auto-generated method stub
}
}
GoSendActivity
This is my GoSendActivity which has edit text view. I want to get the current location on edttxt_from text view.
public class GoSend extends AppCompatActivity {
LatLng latLng;
private GoogleMap mMap;
MarkerOptions markerOptions;
LinearLayout ll;
Toolbar toolbar;
EditText editTextLocation;
EditText edtxt_from;
EditText edtxt_to;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gosendlayout);
setUI();
if (Build.VERSION.SDK_INT >= 21) {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark));
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
public void setUI() {
ll = (LinearLayout) findViewById(R.id.LinearLayoutGoSend);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("GO-SEND");
try {
if (mMap == null) {
mMap = ((MapFragment) getFragmentManager().
findFragmentById(R.id.map)).getMap();
}
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
mMap.setMyLocationEnabled(true);
} catch (Exception e) {
e.printStackTrace();
}
edtxt_from=(EditText)findViewById(R.id.editText_from);
edtxt_to=(EditText)findViewById(R.id.editText_to);
edtxt_from.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(getApplicationContext(),PickLocationActivity.class);
startActivity(i);
}
});
edtxt_to.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(getApplicationContext(),PickLocationActivity.class);
startActivity(i);
}
});
}
}
Location class
public class Location {
private int id;
private String mFrom_loc;
private String mTo_loc;
private String mFromloc_details;
private String mToloc_details;
private String mItems_details;
public Location(int id,String mFrom_loc,String mFromloc_details,String mTo_loc,String mToloc_details,String mItems_details)
{
this.id=id;
this.mFrom_loc=mFrom_loc;
this.mFromloc_details=mFromloc_details;
this.mTo_loc=mTo_loc;
this.mToloc_details=mToloc_details;
this.mItems_details=mItems_details;
}
public Location(String mFrom_loc){
this.mFrom_loc=mFrom_loc;
}
public Location(){}
public int getId(int id){return id;}
public String getmFrom_loc(String mFrom_loc){return mFrom_loc;}
public String getmTo_loc(String mTo_loc){return mTo_loc;}
public String getmFromloc_details(String mFromloc_details){return mFromloc_details;}
public String getmToloc_details(String mToloc_details){return mToloc_details;}
public String getmItems_details(String mItems_details){return mItems_details;}
public void setId(){this.id=id;}
public void setmFrom_loc(){this.mFrom_loc=mFrom_loc;}
public void setmTo_loc(){this.mTo_loc=mTo_loc;}
public void setmFromloc_details(){this.mFromloc_details=mFromloc_details;}
public void setmToloc_details(){this.mToloc_details=mToloc_details;}
public void setmItems_details(){this.mItems_details=mItems_details;}
}
How can I achieve this?? Please help..
try this :
useLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ChooseFromMapActivity.this , GoSendActivity.class);
intent.putExtra("Latitude", latitude);
intent.putExtra("Longitude", longitude);
startActivity(intent);
}
});
And inside onCreate of GoSendActivity,get latitude and longitude like this :
Bundle extras = getIntent().getExtras();
if (extras != null) {
double latitude = extras.getDouble("Latitude");
double longitude = extras.getDouble("Longitude");
}
Now you can set latitude and longitude to your edittext edittext.setText(String.valueOf(latitude));
Apart from passing the data to the next activity using intents, you can also use shared preferences, TinyDB lib achieves great results for caching data. Yoou will need to sync this in your gradle file :
compile 'com.mukesh:tinydb:1.0.1'
then in your onCreate in each activity you will be using the same, initialize the tinyDB by passing application context
TinyDB tinyDB = new TinyDB(getApplicationContext());
With that you can store and retrieve any data within the app using a key-value pair,example to store your coordinates, just call :
tinyDB.putDouble("latitude",latitude);
tinyDB.putDouble("longitude",longitude);
And you can retrieve the data this way:
double latitude = tinyDB.getDouble("latitude");
double longitude = tinyDB.getDouble("longitude");
This class supports all data formats, from Strings,Double,Float and even objects such as ararayLists. Would highly recommend you to try it out.
Make this class as serialisable and put it into intent using bundle.putSerializable("myclaa",location).
Class Location implements Seraializable{
}

How to limit the nearby location search according to the current location using google maps in android?

I am making an android app in which whenever a user selects the clinic option inside the navigation drawer, he/she will be redirected to the in app map (that uses the google maps api key) which will show his/her current location and all the nearby clinics/hospitals with a list at the bottom of the map.
I have tried to implement that but not succeeded. I know there are many questions like this on SO but none of them fulfill my needs.
This is my ClinicFragment java file in which I want to display the map with all the services and a list of nearby hospitals.
public class ClinicFragment extends FragmentActivity implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListener{
public static final String TAG = ClinicFragment.class.getSimpleName();
/*
* Define a request code to send to Google Play services
* This code is returned in Activity.onActivityResult
*/
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.clinic_fragment);
setUpMapIfNeeded();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(Places.GEO_DATA_API)
.addApi(Places.PLACE_DETECTION_API)
.addApi(LocationServices.API)
.build();
// Create the LocationRequest object
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(10 * 1000) // 10 seconds, in milliseconds
.setFastestInterval(1 * 1000); // 1 second, in milliseconds
new GetPlaces(this, getListView()).execute();
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
mGoogleApiClient.connect();
}
#Override
protected void onPause() {
super.onPause();
if (mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
mGoogleApiClient.disconnect();
}
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
private void setUpMap() {
mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
}
private void handleNewLocation(Location location) {
Log.d(TAG, location.toString());
double currentLatitude = location.getLatitude();
double currentLongitude = location.getLongitude();
LatLng latLng = new LatLng(currentLatitude, currentLongitude);
//mMap.addMarker(new MarkerOptions().position(new LatLng(currentLatitude, currentLongitude)).title("Current Location"));
MarkerOptions options = new MarkerOptions()
.position(latLng)
.title("I am here!");
mMap.addMarker(options);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.getUiSettings().setMyLocationButtonEnabled(true);
mMap.getUiSettings().setRotateGesturesEnabled(true);
}
#Override
public void onConnected(Bundle bundle) {
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (location == null) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
else {
handleNewLocation(location);
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
/*
* Google Play services can resolve some errors it detects.
* If the error has a resolution, try sending an Intent to
* start a Google Play services activity that can resolve
* error.
*/
if (connectionResult.hasResolution()) {
try {
// Start an Activity that tries to resolve the error
connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
/*
* Thrown if Google Play services canceled the original
* PendingIntent
*/
} catch (IntentSender.SendIntentException e) {
// Log the error
e.printStackTrace();
}
} else {
/*
* If no resolution is available, display a dialog to the
* user with the error.
*/
Log.i(TAG, "Location services connection failed with code " + connectionResult.getErrorCode());
}
}
#Override
public void onLocationChanged(Location location) {
handleNewLocation(location);
}
class GetPlaces extends AsyncTask<Void, Void, Void> {
private ProgressDialog dialog;
private Context context;
private String[] placeName;
private String[] imageUrl;
private ListView listView;
public GetPlaces(Context context, ListView listView) {
// TODO Auto-generated constructor stub
this.context = context;
this.listView = listView;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
dialog.dismiss();
listView.setAdapter(new ArrayAdapter<String>(context, android.R.layout.simple_expandable_list_item_1,placeName));
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialog = new ProgressDialog(context);
dialog.setCancelable(true);
dialog.setMessage("Loading..");
dialog.isIndeterminate();
dialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
PlacesServices service = new PlacesServices("paste your place api key");
List<Place> findPlaces = service.findPlaces(28.632808,77.218276,"hospital"); // hospiral for hospital
// atm for ATM
placeName = new String[findPlaces.size()];
imageUrl = new String[findPlaces.size()];
for (int i = 0; i < findPlaces.size(); i++) {
Place placeDetail = findPlaces.get(i);
placeDetail.getIcon();
System.out.println( placeDetail.getName());
placeName[i] =placeDetail.getName();
imageUrl[i] =placeDetail.getIcon();
}
return null;
}
}
Place.java
public class Place {
private String id;
private String icon;
private String name;
private String vicinity;
private Double latitude;
private Double longitude;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
public Double getLatitude() {
return latitude;
}
public void setLatitude(Double latitude) {
this.latitude = latitude;
}
public Double getLongitude() {
return longitude;
}
public void setLongitude(Double longitude) {
this.longitude = longitude;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getVicinity() {
return vicinity;
}
public void setVicinity(String vicinity) {
this.vicinity = vicinity;
}
static Place jsonToPontoReferencia(JSONObject pontoReferencia) {
try {
Place result = new Place();
JSONObject geometry = (JSONObject) pontoReferencia.get("geometry");
JSONObject location = (JSONObject) geometry.get("location");
result.setLatitude((Double) location.get("lat"));
result.setLongitude((Double) location.get("lng"));
result.setIcon(pontoReferencia.getString("icon"));
result.setName(pontoReferencia.getString("name"));
result.setVicinity(pontoReferencia.getString("vicinity"));
result.setId(pontoReferencia.getString("id"));
return result;
} catch (JSONException ex) {
Logger.getLogger(Place.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
#Override
public String toString() {
return "Place{" + "id=" + id + ", icon=" + icon + ", name=" + name + ", latitude=" + latitude + ", longitude=" + longitude + '}';
}
PlacesServices.java
public class PlacesServices {
private String API_KEY;
public PlacesServices(String apikey) {
this.API_KEY = apikey;
}
public void setApiKey(String apikey) {
this.API_KEY = apikey;
}
public List<Place> findPlaces(double latitude, double longitude,String placeSpacification)
{
String urlString = makeUrl(latitude, longitude,placeSpacification);
try {
String json = getJSON(urlString);
System.out.println(json);
JSONObject object = new JSONObject(json);
JSONArray array = object.getJSONArray("results");
ArrayList<Place> arrayList = new ArrayList<Place>();
for (int i = 0; i < array.length(); i++) {
try {
Place place = Place.jsonToPontoReferencia((JSONObject) array.get(i));
Log.v("Places Services ", "" + place);
arrayList.add(place);
} catch (Exception e) {
}
}
return arrayList;
} catch (JSONException ex) {
Logger.getLogger(PlacesServices.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
//https://maps.googleapis.com/maps/api/place/search/json?location=28.632808,77.218276&radius=500&types=atm&sensor=false&key=apikey
private String makeUrl(double latitude, double longitude,String place) {
StringBuilder urlString = new StringBuilder("https://maps.googleapis.com/maps/api/place/search/json?");
if (place.equals("")) {
urlString.append("&location=");
urlString.append(Double.toString(latitude));
urlString.append(",");
urlString.append(Double.toString(longitude));
urlString.append("&radius=1000");
// urlString.append("&types="+place);
urlString.append("&sensor=false&key=" + API_KEY);
} else {
urlString.append("&location=");
urlString.append(Double.toString(latitude));
urlString.append(",");
urlString.append(Double.toString(longitude));
urlString.append("&radius=1000");
urlString.append("&types="+place);
urlString.append("&sensor=false&key=" + API_KEY);
}
return urlString.toString();
}
protected String getJSON(String url) {
return getUrlContents(url);
}
private String getUrlContents(String theUrl)
{
StringBuilder content = new StringBuilder();
try {
URL url = new URL(theUrl);
URLConnection urlConnection = url.openConnection();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()), 8);
String line;
while ((line = bufferedReader.readLine()) != null)
{
content.append(line + "\n");
}
bufferedReader.close();
}
catch (Exception e)
{
e.printStackTrace();
}
return content.toString();
}
I am able to get the current location but limiting the nearby search to hospital and getting the list of those nearby hospitals with their details is not happening.
Please can anyone help me out with this.
Thank you

Categories