Intent among three activities error - android

I searched all the question about android intent among three activities in stack overflow, but there were unfortunate without the expect occasion i faced, the first activity which include a simple button but it does't matter and through that activity i pass a data to the second activity, and i want to click the textView(a button) and pass some data to the third activity, the total program is too long and here is the snippet:
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.btn_search:
Intent third = new Intent(this, ThirdActivity.class);
startActivity(third);
break;
default:
break;
}
}
what i expect is that click the button and jump to the third activity, but actually every click it back to the first activity, i am curious if i can not use intent in the second activity?but i think it's ridiculous. Is there any suggestion about this problem.
UPDATE:here is the whole class but there are many empty implementation, and SDK is gaode map, so don't care about the total logic and just pay attention on the onclick event:
public class AroundSearchActivity extends Activity implements AMap.OnMapClickListener,
AMap.OnMarkerClickListener, AMap.OnInfoWindowClickListener, AMap.InfoWindowAdapter,
View.OnClickListener, PoiSearch.OnPoiSearchListener, LocationSource, AMapLocationListener
{
private AMap map;
private MapView mapView;
private AMapLocation mapLocation;
private AMapLocationClient mapLocationClient;
private AMapLocationClientOption mapLocationClientOption;
private OnLocationChangedListener locationChangedListener;
private double latitude;
private double longitude;
private double previousLatitude = 0;
private Marker currentMarker;
private RelativeLayout detail;
private TextView name;
private TextView address;
private EditText input_text;
private PoiSearch poiSearch;
private PoiSearch.Query query;
private PoiResult result;
private ArrayList<PoiItem> poiItems;
private Marker mLastMarker;
private Marker detailMarker;
private MyPoiOverlay poiOverlay;
private String searchStr;
private int[] showMarkers = {
R.drawable.poi_marker_1,R.drawable.poi_marker_2,R.drawable.poi_marker_3,R.drawable.poi_marker_4,R.drawable.poi_marker_5,
R.drawable.poi_marker_6,R.drawable.poi_marker_7,R.drawable.poi_marker_8,R.drawable.poi_marker_9,R.drawable.poi_marker_10,
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.poiaroundsearch_activity);
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
init();
}
public void init(){
if (map == null){
map = mapView.getMap();
}
setUpMap();
map.setOnMapClickListener(this);
map.setOnMarkerClickListener(this);
map.setOnInfoWindowClickListener(this);
map.setInfoWindowAdapter(this);
TextView search = (TextView) findViewById(R.id.btn_search);
search.setOnClickListener(this);
setup();
}
public void setup(){
detail = (RelativeLayout) findViewById(R.id.poi_detail);
detail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//toggle detail click event
Toast.makeText(AroundSearchActivity.this, "hello", Toast.LENGTH_SHORT).show();
}
});
name = (TextView) findViewById(R.id.poi_name);
address = (TextView) findViewById(R.id.poi_address);
input_text = (EditText) findViewById(R.id.input_edittext);
}
#Override
protected void onResume() {
super.onResume();
mapView.onResume();
searchMap();
}
#Override
protected void onPause() {
super.onPause();
mapView.onDestroy();
deactivate();
}
public void setUpMap(){
map.setLocationSource(this);
map.getUiSettings().setMyLocationButtonEnabled(true);
map.setMyLocationEnabled(true);
map.setMyLocationType(AMap.LOCATION_TYPE_LOCATE);
}
#Override
protected void onDestroy() {
super.onDestroy();
locationChangedListener = null;
if (mapLocationClient != null){
mapLocationClient.stopLocation();
mapLocationClient.onDestroy();
}
mapLocationClient = null;
}
#Override
public void onLocationChanged(AMapLocation aMapLocation) {
if (locationChangedListener != null && aMapLocation != null){
if(aMapLocation.getErrorCode() == 0){
latitude = aMapLocation.getLatitude();
longitude = aMapLocation.getLongitude();
locationChangedListener.onLocationChanged(aMapLocation);
Log.i("CurrentLocation", "latitude is " + latitude + " ,longitude is:" + longitude);//get current latitude and longitude
if (currentMarker != null) currentMarker = null;
currentMarker = map.addMarker(new MarkerOptions().
position(new LatLng(latitude, longitude))
.icon(null)
.draggable(true));
currentMarker.showInfoWindow();
map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude), 16));
if (previousLatitude == 0){
searchMap();
}else{
String pre = String.valueOf(previousLatitude);
String a = pre.substring(pre.indexOf(".") + 1, pre.indexOf(".") + 4);
String cur = String.valueOf(latitude);
String b = cur.substring(cur.indexOf(".") + 1, cur.indexOf(".") + 4);
if (!a.equals(b)){
searchMap();
}
}
previousLatitude = latitude;
}else{
int errorCode = aMapLocation.getErrorCode();
Toast.makeText(this, "定位失败:"+errorCode, Toast.LENGTH_SHORT);
}
}
}
#Override
public View getInfoWindow(Marker marker) {
return null;
}
#Override
public View getInfoContents(Marker marker) {
return null;
}
#Override
public void activate(OnLocationChangedListener onLocationChangedListener) {
locationChangedListener = onLocationChangedListener;
if (mapLocationClient == null){
mapLocationClient = new AMapLocationClient(this);
mapLocationClientOption = new AMapLocationClientOption();
mapLocationClient.setLocationListener(this);mapLocationClientOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
mapLocationClient.setLocationOption(mapLocationClientOption);
mapLocationClient.startLocation();
}
}
#Override
public void deactivate() {
locationChangedListener = null;
if (mapLocationClient != null){
mapLocationClient.stopLocation();
mapLocationClient.onDestroy();
}
mapLocationClient = null;
}
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.btn_search:
Intent third = new Intent(this, ThirdActivity.class);
startActivity(third);
break;
default:
break;
}
}
#Override
public void onInfoWindowClick(Marker marker) {
}
#Override
public void onMapClick(LatLng latLng) {
whetherToShowInfo(false);
if (mLastMarker != null){
resetLastMarker();
}
}
#Override
public boolean onMarkerClick(Marker marker) {
if (marker.getObject() != null){
//whether to show the marker detail information
whetherToShowInfo(true);
//get the current location
PoiItem currentItem = (PoiItem) marker.getObject();
//aim at the next marker and preserve the current marker
if (mLastMarker == null){
mLastMarker = marker;
}else {
resetLastMarker();
mLastMarker = marker;
}
detailMarker = marker;
detailMarker.setIcon(BitmapDescriptorFactory.fromResource(R.drawable.poi_marker_pressed));
setPoiMarkerContent(currentItem);
}else {
whetherToShowInfo(false);
resetLastMarker();
}
return true;
}
#Override
public void onPoiSearched(PoiResult poiResult, int errorCode) {
if (errorCode == 1000){
if (poiResult != null && poiResult.getQuery() != null){
if (poiResult.getQuery().equals(query)){//判断是不是同一组查询
result = poiResult;//将搜索结果赋值给result
poiItems = result.getPois();
//列出所有poi搜索结果
for (int i = 0; i < poiItems.size(); i++){
Log.i("result"+i, poiItems.get(i).getSnippet());
}
List<SuggestionCity> suggestionCities = result.getSearchSuggestionCitys();
if (poiItems != null && poiItems.size() > 0){
whetherToShowInfo(false);
if (mLastMarker != null) {
resetLastMarker();
}
if (poiOverlay != null){
poiOverlay.removeFromMap();
}
map.clear();
poiOverlay = new MyPoiOverlay(this, map, poiItems);
poiOverlay.addToMap();
poiOverlay.zoomToSpan();//move to the current scene
map.addMarker(new MarkerOptions().anchor(0.5f, 0.5f)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.point4))
.draggable(false)
.position(new LatLng(latitude, longitude)));
}else{
if (suggestionCities != null && suggestionCities.size() > 0){
showSuggestCity(suggestionCities);
}
}
}
}else {
Toast.makeText(this, "Sorry! No result match your request", Toast.LENGTH_SHORT).show();
}
}else {
Log.e("errorInfo", "Search failed:" + errorCode);
}
}
#Override
public void onPoiItemSearched(PoiItem poiItem, int i) {
}
public void whetherToShowInfo(boolean w){
if (w){
detail.setVisibility(View.VISIBLE);
}else{
detail.setVisibility(View.GONE);
}
}
public void resetLastMarker(){
int index = poiOverlay.getPoiIndex(mLastMarker);
if (index < 10){
mLastMarker.setIcon(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getResources(), showMarkers[index])));
}else{
mLastMarker.setIcon(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.marker_other_highlight)));
}
mLastMarker = null;
}
public void showSuggestCity(List<SuggestionCity> suggestionCities){
String information = "City information/n";
for (int i = 0; i < suggestionCities.size(); i++){
information += "City name" + suggestionCities.get(i).getCityName() +
", City administrative code::" + suggestionCities.get(i).getAdCode();
}
Toast.makeText(this, information, Toast.LENGTH_SHORT);
}
public void searchMap(){
Toast.makeText(this, searchStr, Toast.LENGTH_SHORT).show();
Intent intent = getIntent();
searchStr = intent.getStringExtra("keyword");
int currentPage = 0;
query = new PoiSearch.Query(searchStr.trim(), "", "Beijing");
query.setPageSize(20);
query.setPageNum(currentPage);
LatLonPoint lp = new LatLonPoint(latitude, longitude);
if (lp != null){
poiSearch = new PoiSearch(this, query);
poiSearch.setOnPoiSearchListener(this);
poiSearch.setBound(new PoiSearch.SearchBound(lp, 2000, true));
poiSearch.searchPOIAsyn();
}
}
public void setPoiMarkerContent(PoiItem item){
name.setText(item.getTitle());
address.setText(item.getSnippet());
}
}

Related

How to add multiple pins to mapView after gettng JSON data

I'm making an app to display the five nearest Subway stations. I'm able to get the names of the stations back and populate a list view with the data.
I'm getting lng&lat from the API and would like to add pins to the map using these coordinates. I've got the map working, I'm able to display a single pin, but not multiple pins. A point in the correct direction would be much appreciated - Please see code below.
public class nearMe extends AppCompatActivity implements OnMapReadyCallback {
private MapView mapView;
public GoogleMap gmap;
private static final String MAP_VIEW_BUNDLE_KEY = "MapViewBundleKey";
// Location Co-ordinates
private String lat = "";
private String lng = "";
LocationManager locationManager;
LocationListener locationListener;
private List<Station> stationList = new ArrayList<>();
private RecyclerView recyclerView;
private stationAdapter mAdapter;
/* LOCATION STUFF */
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
startListening();
}
}
public void startListening() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
}
}
public void updateLocationInfo(Location location) {
lat = "" + location.getLatitude();
lng = "" + location.getLongitude();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_location, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// int id = item.getItemId();
getNearestStations();
Toast.makeText(this, "Location Updated!", Toast.LENGTH_SHORT).show();
return super.onOptionsItemSelected(item);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_near_me);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mAdapter = new stationAdapter(stationList);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter);
// onClick
recyclerView.addOnItemTouchListener(new TouchListener(getApplicationContext(), recyclerView, new ClickListener() {
#Override
public void onClick(View view, int position) {
// Toast.makeText(getApplicationContext(), stationList.get(position).getStation() + "", Toast.LENGTH_SHORT).show();
String findStation = stationList.get(position).getStation();
// Toast.makeText(nearMe.this, bob, Toast.LENGTH_SHORT).show();
Uri gmmIntentUri = Uri.parse("google.navigation:q="+findStation+"underground station+London&mode=w");
Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri);
mapIntent.setPackage("com.google.android.apps.maps");
mapIntent.setFlags(mapIntent.FLAG_ACTIVITY_CLEAR_TOP);
if (mapIntent.resolveActivity(getPackageManager()) != null) {
startActivity(mapIntent);
}
}
}));
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
updateLocationInfo(location);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
if (Build.VERSION.SDK_INT < 23) {
startListening();
} else {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
} else {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
updateLocationInfo(location);
}
}
}
// insert Stations in to recycler
getNearestStations();
//map
Bundle mapViewBundle = null;
if (savedInstanceState != null) {
mapViewBundle = savedInstanceState.getBundle(MAP_VIEW_BUNDLE_KEY);
}
mapView = (MapView) findViewById(R.id.map_view);
mapView.onCreate(mapViewBundle);
mapView.getMapAsync(this);
}
// clear adapter before adding
public void clear() {
int size = this.stationList.size();
this.stationList.clear();
mAdapter.notifyItemRangeRemoved(0, size);
}
public void getNearestStations(){
RequestQueue queue = Volley.newRequestQueue(this);
String url = "https://transportapi.com/v3/uk/tube/stations/near.json?app_id=157c4895&app_key=091697cea8bae89519dd02ebb318fc51&lat=" + lat + "&lon=" + lng + "&rpp=5";
final StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("stations");
// Call 'Clear' method to clear mAdapter before adding new data
clear();
if (jsonArray.length() > 0) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jObject = jsonArray.getJSONObject(i);
String station = jObject.getString("name");
Station newStation = new Station(station);
stationList.add(newStation);
mAdapter.notifyDataSetChanged();
double longitude = Double.parseDouble(lng);
double latitude = Double.parseDouble(lat);
gmap.addMarker(new MarkerOptions()
.position(new LatLng(latitude, longitude))
.title(station));
}
}else{
Station newStation = new Station("No stations near");
stationList.add(newStation);
mAdapter.notifyDataSetChanged();
// Show a diaog
AlertDialog alertDialog = new AlertDialog.Builder(nearMe.this).create();
alertDialog.setTitle("No Stations Found");
alertDialog.setMessage("You are either not in London or you have no network connectivity.");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}); alertDialog.show();
}
} catch (JSONException e) { }
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(stringRequest);
}
// maps
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Bundle mapViewBundle = outState.getBundle(MAP_VIEW_BUNDLE_KEY);
if (mapViewBundle == null) {
mapViewBundle = new Bundle();
outState.putBundle(MAP_VIEW_BUNDLE_KEY, mapViewBundle);
}
mapView.onSaveInstanceState(mapViewBundle);
}
#Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
#Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
#Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
#Override
protected void onPause() {
mapView.onPause();
super.onPause();
}
#Override
protected void onDestroy() {
mapView.onDestroy();
super.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
#Override
public void onMapReady(GoogleMap googleMap) {
}
}
Let's say your API returns data in the markers array.
for(int i = 0 ; i < markers.size() ; i++ ) {
createMarker(markers.get(i).getLatitude(), markers.get(i).getLongitude(), markers.get(i).getTitle(), markers.get(i).getSnippet(), markers.get(i).getIconResID());
}
...
protected Marker createMarker(double latitude, double longitude, String title, String snippet, int iconResID) {
return googleMap.addMarker(new MarkerOptions()
.position(new LatLng(latitude, longitude))
.anchor(0.5f, 0.5f)
.title(title)
.snippet(snippet);
.icon(BitmapDescriptorFactory.fromResource(iconResID)));
}

Implementing Google Maps Directions API with Place Autocomplete in android

I've implemented the Google Maps Directions API with the help of this tutorial https://github.com/hiepxuan2008/GoogleMapDirectionSimple/tree/master/app/src/main/java/Modules
where two EditText fields are used for Origin and Destination but this seems a little bit confusing and sometimes gives wrong directions when there are two places with same name. Later I foun out that there is Place Autocomplete feature. So, my question is can I modify the existing code to get place autocomplete instead of EditText or I should start all over again. If it is possible, how can I do this?
public class MapViewFragment extends Fragment implements OnMapReadyCallback, DirectionFinderListener {
private Button btnFindPath;
private EditText etOrigin;
private EditText etDestination;
private ProgressDialog progressDialog;
private List<Marker> originMarkers = new ArrayList<>();
private List<Marker> destinationMarkers = new ArrayList<>();
private List<Polyline> polylinePaths = new ArrayList<>();
GoogleMap mGoogleMap;
MapView mMapView;
View mView;
public MapViewFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
mView = inflater.inflate(R.layout.fragment_map_view, container, false);
btnFindPath = (Button) mView.findViewById(R.id.btnFindPath);
etOrigin = (EditText) mView.findViewById(R.id.etOrigin);
etDestination = (EditText) mView.findViewById(R.id.etDestination);
btnFindPath.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendRequest();
}
});
return mView;
}
private void sendRequest() {
String origin = etOrigin.getText().toString();
String destination = etDestination.getText().toString();
if (origin.isEmpty()) {
Toast.makeText(getActivity(), "Please enter origin address!", Toast.LENGTH_SHORT).show();
return;
}
if (destination.isEmpty()) {
Toast.makeText(getActivity(), "Please enter destination address!", Toast.LENGTH_SHORT).show();
return;
}
try {
new DirectionFinder(this, origin, destination).execute();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mMapView = (MapView) mView.findViewById(R.id.map);
if (mMapView != null){
mMapView.onCreate(null);
mMapView.onResume();
mMapView.getMapAsync(this);
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
MapsInitializer.initialize(this.getActivity());
mGoogleMap = googleMap;
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
googleMap.addMarker(new MarkerOptions().position(new LatLng(27.717245, 85.323960)).title("Yo ho Kathmandu University") .snippet("I study Here"));
CameraPosition Liberty = CameraPosition.builder().target(new LatLng(27.717245, 85.323960)).zoom(16).bearing(0).tilt(45).build();
googleMap.moveCamera(CameraUpdateFactory.newCameraPosition(Liberty));
googleMap.setMyLocationEnabled(true);
}
#Override
public void onDirectionFinderStart() {
progressDialog = ProgressDialog.show(getActivity(), "Please wait.",
"Finding direction..!", true);
if (originMarkers != null) {
for (Marker marker : originMarkers) {
marker.remove();
}
}
if (destinationMarkers != null) {
for (Marker marker : destinationMarkers) {
marker.remove();
}
}
if (polylinePaths != null) {
for (Polyline polyline:polylinePaths ) {
polyline.remove();
}
}
}
#Override
public void onDirectionFinderSuccess(List<Route> routes) {
progressDialog.dismiss();
polylinePaths = new ArrayList<>();
originMarkers = new ArrayList<>();
destinationMarkers = new ArrayList<>();
for (Route route : routes) {
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(route.startLocation, 16));
((TextView) getView().findViewById(R.id.tvDuration)).setText(route.duration.text);
((TextView) getView().findViewById(R.id.tvDistance)).setText(route.distance.text);
originMarkers.add(mGoogleMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_media_pause))
.title(route.startAddress)
.position(route.startLocation)));
destinationMarkers.add(mGoogleMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_media_play))
.title(route.endAddress)
.position(route.endLocation)));
PolylineOptions polylineOptions = new PolylineOptions().
geodesic(true).
color(Color.BLUE).
width(10);
for (int i = 0; i < route.points.size(); i++)
polylineOptions.add(route.points.get(i));
polylinePaths.add(mGoogleMap.addPolyline(polylineOptions));
}
}
}
etOrigin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
findPlace();
}
});
etDestination.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
findPlace2();
}
});
private void findPlace2() {
try {
Intent intent = new PlaceAutocomplete
.IntentBuilder(PlaceAutocomplete.MODE_OVERLAY)
.build(this);
startActivityForResult(intent, 2);
} catch (GooglePlayServicesRepairableException | GooglePlayServicesNotAvailableException e) {
// TODO: Handle the error.
}
}
private void findPlace() {
try {
Intent intent = new PlaceAutocomplete
.IntentBuilder(PlaceAutocomplete.MODE_OVERLAY)
.build(this);
startActivityForResult(intent, 1);
} catch (GooglePlayServicesRepairableException | GooglePlayServicesNotAvailableException e) {
// TODO: Handle the error.
}
}
// A place has been received; use requestCode to track the request.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if (resultCode == RESULT_OK) {
// retrive the data by using getPlace() method.
Place place = PlaceAutocomplete.getPlace(this, data);
Log.e("Tag", "Place: " + place.getAddress() + place.getPhoneNumber());
((EditText) findViewById(R.id.etLokasiAwal))
.setText(place.getName());
} else if (resultCode == PlaceAutocomplete.RESULT_ERROR) {
Status status = PlaceAutocomplete.getStatus(this, data);
// TODO: Handle the error.
Log.e("Tag", status.getStatusMessage());
} else if (resultCode == RESULT_CANCELED) {
// The user canceled the operation.
}
} else if (requestCode == 2) {
if (resultCode == RESULT_OK) {
// retrive the data by using getPlace() method.
Place place = PlaceAutocomplete.getPlace(this, data);
Log.e("Tag", "Place: " + place.getAddress() + place.getPhoneNumber());
((EditText) findViewById(R.id.etLokasiAkhir))
.setText(place.getName());
} else if (resultCode == PlaceAutocomplete.RESULT_ERROR) {
Status status = PlaceAutocomplete.getStatus(this, data);
// TODO: Handle the error.
Log.e("Tag", status.getStatusMessage());
} else if (resultCode == RESULT_CANCELED) {
// The user canceled the operation.
}
}
}
Hope this can help you,
And make sure, at your edit text, set android:focusable="false"

Android Realm Google Maps Memory Leak

My main class application retrieves data using Retrofit and writes to a POJO ordinary Realm object. Then run the second Activity (MapsActivity) where I set the map, filter the contents of the Realm object for the relevant data. Everything works.
I will add that the Realm object contains over 6600 rows so it is big. And unfortunately I feel I have leaks of memory. Each time you start MapsActivity (going back to MainActivity, selecting another category, and passing it to MapsActivity), the heap looks awful. This is shown in the attached image. I will add that the application works much better when I do not use the Realm object at all, I only do the second Retrofit call in the MapsActivity class. This solution unfortunately doubles my work (in Main and Maps I do exactly the same thing) and I want to avoid this. Maybe someone will see where I have a leak and why the program is slowing down.
My Main:
package com.flex.sklepik;
public class MainActivity extends AppCompatActivity {
List<String> shopsNames;
ArrayList<RowModel> rowModels;
public static final int REQUEST_GOOGLE_PLAY_SERVICES = 1972;
public Realm mRealm;
#BindView(R.id.toolbar_layout)
CollapsingToolbarLayout toolbarLayout;
#BindView(R.id.app_bar)
AppBarLayout appBar;
private ShopsAdapter adapter;
#BindView(R.id.recycler_view)
RecyclerView recyclerView;
private ProgressDialog progressDialog;
private Dialog errorDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
ButterKnife.bind(this);
startRegistrationService();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ConnectionDetector connectionDetector = new ConnectionDetector(this);
if (!connectionDetector.isConnection()) {
finish();
}
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 123);
checkPlayServices();
rowModels = new ArrayList<>();
shopsNames = new ArrayList<>();
Realm.init(this);
mRealm = Realm.getDefaultInstance();
initCollapsingToolbar();
Glide.with(getApplicationContext()).load(R.drawable.shoplogo).
into((ImageView) findViewById(R.id.backdrop));
adapter = new ShopsAdapter(MainActivity.this, shopsNames);
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getApplicationContext(), 2);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(adapter);
AsyncTaskRetro asyncTaskRetro = new AsyncTaskRetro();
asyncTaskRetro.execute();
}
private boolean checkPlayServices() {
GoogleApiAvailability googleApiAvailability = GoogleApiAvailability.getInstance();
int resultCode = googleApiAvailability.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (googleApiAvailability.isUserResolvableError(resultCode)) {
if (errorDialog == null) {
errorDialog = googleApiAvailability.getErrorDialog(this, resultCode, 2404);
errorDialog.setCancelable(false);
}
if (!errorDialog.isShowing())
errorDialog.show();
}
}
return resultCode == ConnectionResult.SUCCESS;
}
private class AsyncTaskRetro extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("Czekaj...");
progressDialog.show();
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
progressDialog.hide();
}
#Override
protected Void doInBackground(Void... voids) {
PlacesAPI.Factory.getInstance().getPlaces().enqueue(new Callback<Places>() {
#Override
public void onResponse(Call<Places> call, Response<Places> response) {
for (int i = 0; i < response.body().getPosts().size(); i++) {
RowModel rowModel = new RowModel(response.body().getPosts().get(i).getNazwa(),
Double.parseDouble(response.body().getPosts().get(i).getSzer()),
Double.parseDouble(response.body().getPosts().get(i).getDlug()));
rowModels.add(rowModel);
}
String oldName;
oldName = rowModels.get(0).getName();
shopsNames.add(rowModels.get(0).getName());
mRealm.beginTransaction();
mRealm.copyToRealm(rowModels);
mRealm.commitTransaction();
for (int j = 0; j < rowModels.size(); j++) {
if (rowModels.get(j).getName().equals(oldName)) {
continue;
}
oldName = rowModels.get(j).getName();
shopsNames.add(rowModels.get(j).getName());
}
//sortowanie listy z nazwami sklepow
Collections.sort(shopsNames);
recyclerView.setAdapter(adapter);
}
#Override
public void onFailure(Call<Places> call, Throwable t) {
}
});
return null;
}
}
#Override
protected void onResume() {
recyclerView.setAdapter(adapter);
super.onResume();
}
private void initCollapsingToolbar() {
final CollapsingToolbarLayout collapsingToolbar =
(CollapsingToolbarLayout) findViewById(R.id.toolbar_layout);
collapsingToolbar.setTitle(" ");
AppBarLayout appBarLayout = (AppBarLayout) findViewById(R.id.app_bar);
appBarLayout.setExpanded(true);
// hiding & showing the title when toolbar expanded & collapsed
appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
boolean isShow = false;
int scrollRange = -1;
#Override
public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
if (scrollRange == -1) {
scrollRange = appBarLayout.getTotalScrollRange();
}
if (scrollRange + verticalOffset == 0) {
collapsingToolbar.setTitle(getString(R.string.app_name));
isShow = true;
} else if (isShow) {
collapsingToolbar.setTitle(" ");
isShow = false;
}
}
});
}
private void startRegistrationService() {
GoogleApiAvailability api = GoogleApiAvailability.getInstance();
int code = api.isGooglePlayServicesAvailable(this);
if (code == ConnectionResult.SUCCESS) {
onActivityResult(REQUEST_GOOGLE_PLAY_SERVICES, Activity.RESULT_OK, null);
} else if (api.isUserResolvableError(code) &&
api.showErrorDialogFragment(this, code, REQUEST_GOOGLE_PLAY_SERVICES)) {
// wait for onActivityResult call (see below)
} else {
Toast.makeText(this, api.getErrorString(code), Toast.LENGTH_LONG).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_GOOGLE_PLAY_SERVICES:
if (resultCode == Activity.RESULT_OK) {
}
break;
default:
super.onActivityResult(requestCode, resultCode, data);
}
}
}
Map Class:
public class MapActivity extends FragmentActivity implements OnMapReadyCallback, GoogleMap.OnMarkerClickListener
{
private GoogleMap mMap;
private double naviLat, naviLong;
private double latitude, longitude;
private GoogleApiClient mGoogleApiClient;
#BindView(R.id.adView)
AdView adView;
#BindView(R.id.butnavi)
ImageButton butnavi;
private Location location;
private RealmResults<RowModel> rowModels;
private String shopName;
private Bundle bundle;
private Realm realm;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map2);
ButterKnife.bind(this);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(map);
mapFragment.getMapAsync(this);
bundle = getIntent().getExtras();
shopName = bundle.getString("shopName");
mapFragment.getMapAsync(this);
ActivityCompat.requestPermissions(MapActivity.this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 123);
AdRequest adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);
realm = Realm.getDefaultInstance();
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setOnMarkerClickListener(this);
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Uprawnienia nie przyznane", Toast.LENGTH_SHORT).show();
}
mMap.setMyLocationEnabled(true);
cameraMove();
//po wczytaniu mapy wyciągnij dane z bazy sklepów
realmDatabaseBuild();
}
private void addMarker(double lat, double lon) {
mMap.addMarker(new MarkerOptions().position(new LatLng(lat, lon)));
}
#OnClick(R.id.butnavi)
public void btnNavi() {
if (naviLat + naviLong == 0)
Toast.makeText(this,
"Najpierw wybierz market", Toast.LENGTH_SHORT)
.show();
else {
Intent i = new Intent(Intent.ACTION_VIEW, Uri
.parse("google.navigation:q=" + naviLat + ","
+ naviLong));
startActivity(i);
finish();
System.exit(0);
}
}
private void moveCameraToActualPosition(double lat, double lon) {
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(lat, lon))
.zoom(12).build();
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
private void realmDatabaseBuild() {
rowModels = realm.where(RowModel.class).equalTo("name", shopName).findAll();
if (!rowModels.isEmpty()) {
for (int i = 0; i < rowModels.size(); i++) {
addMarker(rowModels.get(i).getLongitude(), rowModels.get(i).getLattitude());
}
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.mapTypeNormal:
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
break;
case R.id.mapTypeSatellite:
mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
break;
case R.id.mapTypeTerrain:
mMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
break;
case R.id.mapTypeHybrid:
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onBackPressed() {
super.onBackPressed();
mMap.clear();
rowModels = null;
}
#Override
protected void onResume() {
super.onResume();
}
#Override
public boolean onMarkerClick(Marker marker) {
LatLng gps = marker.getPosition();
//ustawienie lat i long dla nawigacji
naviLat = gps.latitude;
naviLong = gps.longitude;
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses;
try {
addresses = geocoder.getFromLocation(gps.latitude, gps.longitude, 1);
String adres = addresses.get(0).getAddressLine(0);
Toast.makeText(this, "Adres: " + adres, Toast.LENGTH_SHORT).show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
public void cameraMove() {
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Uprawnienia nie przyznane", Toast.LENGTH_SHORT).show();
}
Location myLocation = locationManager.getLastKnownLocation(provider);
if (myLocation != null) {
LatLng ll = new LatLng(myLocation.getLatitude(), myLocation.getLongitude());
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(ll)
.zoom(11).build();
mMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
} else {
LatLng ll = new LatLng(52.230625, 21.013129);//WAWA
CameraPosition cp = new CameraPosition.Builder()
.target(ll)
.zoom(10).build();
mMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cp));
}
}
}
And Pojo:
public class RowModel extends RealmObject {
#Required
private String name;
#Required
private Double lattitude, longitude;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getLattitude() {
return lattitude;
}
public void setLattitude(Double lattitude) {
this.lattitude = lattitude;
}
public Double getLongitude() {
return longitude;
}
public void setLongitude(Double longitude) {
this.longitude = longitude;
}
public RowModel(String name, Double lattitude, Double longitude) {
this.name = name;
this.lattitude = lattitude;
this.longitude = longitude;
}
public RowModel() {
}
}

On resume the fragment i am unable to view the marker and animated camera to a location in map

I am working on an app with google maps-v2. Everything is working fine but when i go from the map fragment to other fragment and get back to the map fragment its not adding any marker or animating the camera.
Following is the code for the fragment:
public class MapPane extends Fragment implements DirectionFinderListener {
private static final int PERMISSION_REQUEST_CODE = 1;
ProgressBar progressBar;
// Google Map
private static GoogleMap googleMap;
public static double latitude, longitude;
private Button btnFindPath;
private String sOrigin = "";
private String sDestination = "";
private List<Marker> originMarkers = new ArrayList<>();
private List<Marker> destinationMarkers = new ArrayList<>();
private List<Polyline> polylinePaths = new ArrayList<>();
private ProgressDialog progressDialog;
View v;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// TODO Add your menu entries here
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.map_pane, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.m_directions) {
Fragment frag3 = new DirectionActivity();
android.support.v4.app.FragmentTransaction ft3 = getActivity().getSupportFragmentManager().beginTransaction();
ft3.replace(R.id.content_frame, frag3);
ft3.commit();
}
return super.onOptionsItemSelected(item);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
Log.e("MapPane", "onCreateView()");
v = inflater.inflate(R.layout.activity_maps, container, false);
progressBar = (ProgressBar) v.findViewById(R.id.progressBar);
sOrigin = getArguments().getString("source");
sDestination = getArguments().getString("destination");
Log.e("MapPane ", "Source: " + sOrigin + "Destination: " + sDestination);
Geocoder geocoder = new Geocoder(getActivity());
List<Address> addresses = null;
if (sOrigin.equals(null)) {
Toast.makeText(getActivity(), "Source is empty!", Toast.LENGTH_SHORT).show();
} else {
try {
addresses = geocoder.getFromLocationName(sOrigin, 1);
} catch (IOException e) {
e.printStackTrace();
}
if (addresses.size() > 0) {
latitude = addresses.get(0).getLatitude();
longitude = addresses.get(0).getLongitude();
Log.e("Location Coordinates ", String.valueOf(latitude) + " ," + String.valueOf(longitude));
}
}
btnFindPath = (Button) v.findViewById(R.id.btnFindPath);
progressDialog = new ProgressDialog(v.getContext());
progressDialog.setCancelable(false);
progressDialog.setMessage("Please wait...");
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
try {
// Loading map
initilizeMap();
} catch (Exception e) {
e.printStackTrace();
}
if (!checkPermission()) {
requestPermission();
} else {
zoomToOrigin();
}
btnFindPath.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendRequest();
}
});
return v;
}
private void zoomToOrigin() {
if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
googleMap.setMyLocationEnabled(true);
} else {
// Show rationale and request permission.
}
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
googleMap.getUiSettings().setZoomControlsEnabled(true);
CameraPosition cameraPosition = new CameraPosition.Builder().target(
new LatLng(latitude, longitude)).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
private boolean checkPermission() {
int result = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION);
if (result == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
return false;
}
}
private void requestPermission() {
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSION_REQUEST_CODE);
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case PERMISSION_REQUEST_CODE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(getActivity(), "Permission Granted, Now you can access location data.", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getActivity(), "Permission Granted, Now you can access location data.", Toast.LENGTH_LONG).show();
}
break;
}
}
/**
* function to load map. If map is not created it will create it for you
*/
private void initilizeMap() {
if (googleMap == null) {
googleMap = ((MapFragment) getActivity().getFragmentManager().findFragmentById(
R.id.map)).getMap();
// check if map is created successfully or not
if (googleMap == null) {
Toast.makeText(getContext(),
"Sorry! unable to create maps", Toast.LENGTH_SHORT)
.show();
}
}
}
private void sendRequest() {
try {
new DirectionFinder(this, sOrigin, sDestination).execute();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
#Override
public void onResume() {
initilizeMap();
Log.e("MapPane", "onResume()" + latitude + " ," + longitude);
MarkerOptions marker = new MarkerOptions().position(new LatLng(latitude, longitude))
.title("Nagpur");
googleMap.addMarker(marker);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(latitude, longitude)).zoom(14).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
getView().setFocusableInTouchMode(true);
getView().requestFocus();
getView().setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) {
Fragment fragment = new BDashboard();
FragmentManager fm = getActivity().getSupportFragmentManager();
android.support.v4.app.FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.commit();
return true;
}
return false;
}
});
super.onResume();
}
#Override
public void onDestroyView() {
Log.e("MapPane", "onDestroyView");
try {
MapFragment fragment = ((MapFragment) getActivity().getFragmentManager().findFragmentById(R.id.map));
FragmentTransaction ft = getActivity().getFragmentManager().beginTransaction();
ft.remove(fragment);
ft.commit();
} catch (Exception e) {
}
super.onDestroyView();
}
#Override
public void onDirectionFinderStart() {
progressDialog = ProgressDialog.show(getActivity(), "Please wait.",
"Finding direction..!", true);
if (originMarkers != null) {
for (Marker marker : originMarkers) {
marker.remove();
}
}
if (destinationMarkers != null) {
for (Marker marker : destinationMarkers) {
marker.remove();
}
}
if (polylinePaths != null) {
for (Polyline polyline : polylinePaths) {
polyline.remove();
}
}
}
#Override
public void onDirectionFinderSuccess(List<Route> routes) {
progressDialog.dismiss();
polylinePaths = new ArrayList<>();
originMarkers = new ArrayList<>();
destinationMarkers = new ArrayList<>();
for (Route route : routes) {
((TextView) v.findViewById(R.id.tvDuration)).setText(route.duration.text);
((TextView) v.findViewById(R.id.tvDistance)).setText(route.distance.text);
originMarkers.add(googleMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.start_blue))
.title(route.startAddress)
.position(route.startLocation)));
destinationMarkers.add(googleMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.end_green))
.title(route.endAddress)
.position(route.endLocation)));
PolylineOptions polylineOptions = new PolylineOptions().
geodesic(true).
color(Color.BLUE).
width(10);
for (int i = 0; i < route.points.size(); i++)
polylineOptions.add(route.points.get(i));
polylinePaths.add(googleMap.addPolyline(polylineOptions));
}
}
}
This is the only problem i am facing unless everything is working fine.
Please help me to solve this issue.
Thanks

Indoor Atlas: Searching in a Map

I'm using Indoor Atlas for an educational project based on Android.
I'd like to implement search functionality into a map that I loaded in Indoor Atlas environment, how I can this?
For example I'd like to search a room of specific, apartment, how I can implement this searching functionality?
Thanks for your time
You should mapping the location firstly.
And do test path for making your map more precise.
There is official app of IndoorAtlas, so you can use it.
First you need to map your floor using indooratlas app i.e IndoorAtlas MapCreator 2. Then you can record the coordinates using that app and then you can save the coordinates of the rooms/areas in your server and then can fetch and point it on maps after search.
/*
gimal.adobe.appsbee.com.gimbaladobe.Indooratlasmap
16/12/16
sumit-chakraborty
*/
public class IndoorAtlasMap implements OnMapReadyCallback, GoogleMap.InfoWindowAdapter, GoogleMap.OnInfoWindowClickListener {
private static final String TAG = "IndoorAtlasExample";
private IndoorAtlasCallBack mIndoorAtlasCallBack;
SupportMapFragment mapFragment;
private static final float HUE_IABLUE = 200.0f;
/* used to decide when bitmap should be downscaled */
private static final int MAX_DIMENSION = 1048;
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
private Marker mMarker;
private Marker mMarkerLoc;
private GroundOverlay mGroundOverlay;
private IALocationManager mIALocationManager;
private IAResourceManager mResourceManager;
private IATask<IAFloorPlan> mFetchFloorPlanTask;
private static LatLng latlongfromlistner;
private Target mLoadTarget;
private boolean mCameraPositionNeedsUpdating;
private ArrayList<ListLatlong> latlong;
LayoutInflater inflater = null;
private TextView textViewTitle;
private RelativeLayout rl_custominfo;
public IndoorAtlasMap(IndoorAtlasCallBack mIndoorAtlasCallBack, LayoutInflater inflater) {
this.mIndoorAtlasCallBack = mIndoorAtlasCallBack;
this.inflater = inflater;
}
/**
* Listener that handles location change events.
*/
private IALocationListener mListener = new IALocationListenerSupport() {
/**
* Location changed, move marker and camera position.
*/
#Override
public void onLocationChanged(IALocation location) {
Log.d(TAG, "new location received with coordinates: " + location.getLatitude()
+ "," + location.getLongitude());
System.out.println("!!!!!!aaa" + location.toString());
if (mMap == null) {
// location received before map is initialized, ignoring update here
return;
}
latlongfromlistner = new LatLng(location.getLatitude(), location.getLongitude());
if (mMarker == null) {
// first location, add marker
mMarker = mMap.addMarker(new MarkerOptions().position(latlongfromlistner)
.icon(BitmapDescriptorFactory.defaultMarker(HUE_IABLUE)));
} else {
// move existing markers position to received location
mMarker.setPosition(latlongfromlistner);
}
// our camera position needs updating if location has significantly changed
if (mCameraPositionNeedsUpdating) {
//Create a new CameraPosition
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latlongfromlistner, 19.0f));
mCameraPositionNeedsUpdating = false;
}
mMarker.hideInfoWindow();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
switch (status) {
case IALocationManager.STATUS_CALIBRATION_CHANGED:
String quality = "unknown";
switch (extras.getInt("quality")) {
case IALocationManager.CALIBRATION_POOR:
quality = "Poor";
break;
case IALocationManager.CALIBRATION_GOOD:
quality = "Good";
break;
case IALocationManager.CALIBRATION_EXCELLENT:
quality = "Excellent";
break;
}
MyLog.d(TAG, "Calibration change. Quality: " + quality);
break;
case IALocationManager.STATUS_AVAILABLE:
MyLog.d(TAG, "onStatusChanged: Available");
break;
case IALocationManager.STATUS_LIMITED:
MyLog.d(TAG, "onStatusChanged: Limited");
break;
case IALocationManager.STATUS_OUT_OF_SERVICE:
MyLog.d(TAG, "onStatusChanged: Out of service");
break;
case IALocationManager.STATUS_TEMPORARILY_UNAVAILABLE:
MyLog.d(TAG, "onStatusChanged: Temporarily unavailable");
}
}
};
/**
* Region listener that when:
* <ul>
* <li>region has entered; marks need to move camera and starts
* loading floor plan bitmap</li>
* <li>region has existed; clears marker</li>
* </ul>.
*/
private IARegion.Listener mRegionListener = new IARegion.Listener() {
#Override
public void onEnterRegion(IARegion region) {
System.out.println("!!!!!!aaa enter" + region.toString());
mIndoorAtlasCallBack.hideLoading();
if (region.getType() == IARegion.TYPE_UNKNOWN) {
mIndoorAtlasCallBack.showToast("Moved out of map");
return;
}
// entering new region, mark need to move camera
mCameraPositionNeedsUpdating = true;
final String newId = region.getId();
mIndoorAtlasCallBack.showToast(newId);
fetchFloorPlan(newId);
}
#Override
public void onExitRegion(IARegion region) {
System.out.println("!!!!!!aaa exit" + region.toString());
if (mMarker != null) {
mMarker.remove();
mMarker = null;
}
}
};
public void onCreatePoints(ArrayList<ListLatlong> latlong) {
this.latlong = latlong;
if (null != latlong) {
for (int i = 0; i < latlong.size(); i++) {
String title = latlong.get(i).getLoc() != null ? latlong.get(i).getLoc() : "adobe";
mMarkerLoc = mMap.addMarker(new MarkerOptions().position(latlong.get(i).getLatLng())
.title(title)
.snippet(String.valueOf(latlong.get(i).getId()))
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
}
}
}
/**
* Sets bitmap of floor plan as ground overlay on Google Maps
*/
private void setupGroundOverlay(IAFloorPlan floorPlan, Bitmap bitmap) {
if (mGroundOverlay != null) {
mGroundOverlay.remove();
}
if (mMap != null) {
BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory.fromBitmap(bitmap);
IALatLng iaLatLng = floorPlan.getCenter();
LatLng center = new LatLng(iaLatLng.latitude, iaLatLng.longitude);
GroundOverlayOptions fpOverlay = new GroundOverlayOptions()
.image(bitmapDescriptor)
.position(center, floorPlan.getWidthMeters(), floorPlan.getHeightMeters())
.bearing(floorPlan.getBearing());
mGroundOverlay = mMap.addGroundOverlay(fpOverlay);
}
}
/**
* Download floor plan using Picasso library.
*/
private void fetchFloorPlanBitmap(final IAFloorPlan floorPlan) {
final String url = floorPlan.getUrl();
//saving floor level and floor name
App.getInstance().getAppPreferences().setFloorId(floorPlan.getFloorLevel());
App.getInstance().getAppPreferences().setFloorName(floorPlan.getName());
if (mLoadTarget == null) {
mLoadTarget = new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
Log.d(TAG, "onBitmap loaded with dimensions: " + bitmap.getWidth() + "x"
+ bitmap.getHeight());
setupGroundOverlay(floorPlan, bitmap);
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
// N/A
}
#Override
public void onBitmapFailed(Drawable placeHolderDraweble) {
mIndoorAtlasCallBack.showToast("Failed to load bitmap");
mIndoorAtlasCallBack.hideLoading();
}
};
}
if (null != mIndoorAtlasCallBack.getContext()) {
RequestCreator request = Picasso.with(mIndoorAtlasCallBack.getContext()).load(url);
final int bitmapWidth = floorPlan.getBitmapWidth();
final int bitmapHeight = floorPlan.getBitmapHeight();
if (bitmapHeight > MAX_DIMENSION) {
request.resize(0, MAX_DIMENSION);
} else if (bitmapWidth > MAX_DIMENSION) {
request.resize(MAX_DIMENSION, 0);
}
request.into(mLoadTarget);
}
mIndoorAtlasCallBack.onSuccessIndoorMapLoad();
}
/**
* Fetches floor plan data from IndoorAtlas server.
*/
private void fetchFloorPlan(String id) {
// if there is already running task, cancel it
cancelPendingNetworkCalls();
final IATask<IAFloorPlan> task = mResourceManager.fetchFloorPlanWithId(id);
task.setCallback(new IAResultCallback<IAFloorPlan>() {
#Override
public void onResult(IAResult<IAFloorPlan> result) {
if (result.isSuccess() && result.getResult() != null) {
// retrieve bitmap for this floor plan metadata
fetchFloorPlanBitmap(result.getResult());
} else {
// ignore errors if this task was already canceled
if (!task.isCancelled()) {
// do something with error
mIndoorAtlasCallBack.showToast("loading floor plan failed: ");
// remove current ground overlay
if (mGroundOverlay != null) {
mGroundOverlay.remove();
mGroundOverlay = null;
}
}
}
}
}, Looper.getMainLooper()); // deliver callbacks using main looper
// keep reference to task so that it can be canceled if needed
mFetchFloorPlanTask = task;
}
/**
* Helper method to cancel current task if any.
*/
private void cancelPendingNetworkCalls() {
if (mFetchFloorPlanTask != null && !mFetchFloorPlanTask.isCancelled()) {
mFetchFloorPlanTask.cancel();
}
}
#Override
public void onMapReady(GoogleMap mMap) {
this.mMap = mMap;
mMap.setInfoWindowAdapter(this);
mMap.setOnInfoWindowClickListener(this);
}
public void onDestroyView() {
mIALocationManager.removeLocationUpdates(mListener);
mIALocationManager.registerRegionListener(mRegionListener);
onDestroy();
}
public void onDestroy() {
mIALocationManager.destroy();
System.out.println("!!!!!!aaa" + "onDestroyView");
if (null != mMarker) {
mMarker.remove();
}
if (null != mMarkerLoc) {
mMarkerLoc.remove();
}
mIndoorAtlasCallBack.hideLoading();
}
public void onPause() {
mIndoorAtlasCallBack.hideLoading();
}
public void onResume() {
mIALocationManager.requestLocationUpdates(IALocationRequest.create(), mListener);
mCameraPositionNeedsUpdating = true;
}
public void onIndoorAtlasInit(int map_container) {
mIndoorAtlasCallBack.showLoading(mIndoorAtlasCallBack.getContext().getResources().getString(R.string.loading_msg));
FragmentManager fm = mIndoorAtlasCallBack.getChildFragmentManager();
mapFragment = (SupportMapFragment) fm.findFragmentById(R.id.map_container);
if (mapFragment == null) {
mapFragment = SupportMapFragment.newInstance();
fm.beginTransaction().replace(map_container, mapFragment).commit();
}
mapFragment.getMapAsync(this);
Bundle extras = new Bundle(2);
extras.putString(IALocationManager.EXTRA_API_KEY,
App.getInstance().getAppPreferences().getApiKey());
extras.putString(IALocationManager.EXTRA_API_SECRET,
App.getInstance().getAppPreferences().getSecretkey());
mIALocationManager = IALocationManager.create(mIndoorAtlasCallBack.getContext(), extras);
final String floorPlanId = App.getInstance().getAppPreferences().getFloorPlanId();
if (!TextUtils.isEmpty(floorPlanId)) {
final IALocation location = IALocation.from(IARegion.floorPlan(floorPlanId));
mIALocationManager.setLocation(location);
}
mResourceManager = IAResourceManager.create(mIndoorAtlasCallBack.getContext(), extras);
mIALocationManager.requestLocationUpdates(IALocationRequest.create(), mListener);
mIALocationManager.registerRegionListener(mRegionListener);
}
#Override
public View getInfoWindow(final Marker marker) {
View v = inflater.inflate(R.layout.mapinfowindow, null);
if (marker != null && (marker.getTitle() != null && marker.getTitle().length() > 0)) {
MyLog.sout("!!!!oninfowindow", marker.getSnippet());
textViewTitle = (TextView) v.findViewById(R.id.textViewTitle);
rl_custominfo = (RelativeLayout) v.findViewById(R.id.rl_custominfo);
textViewTitle.setText(marker.getTitle());
textViewTitle.setVisibility(View.VISIBLE);
rl_custominfo.setVisibility(View.VISIBLE);
} else{
return null;
}
return (v);
}
#Override
public View getInfoContents(Marker marker) {
return null;
}
#Override
public void onInfoWindowClick(Marker marker) {
MyLog.sout("!!!!oninfo", marker.getSnippet());
LatLng latlng = marker.getPosition();
Double distance = CalculateDistancex.CalculationByDistance(latlng,latlongfromlistner) ;
distance = distance*100;
distance = Double.valueOf(Math.round(distance));
distance = distance /100;
if(null !=marker) {
mIndoorAtlasCallBack.onClickFromInfoWindow(marker.getSnippet(), distance);
}
}
}

Categories

Resources