I'm developing an app with a menu on top with some buttons inside that menu. I'm trying to add google maps to one of the button, but I'm not very successful. I was following this tutorial but instead of implementig google maps directly into MainActivity
I added them into a fragment that is launched when button is pressed. All worked fine. When I press the button the maps load and they work as they should. When I press the home button to go back to MainActivity
it works perfectly, but when I want to load maps again it gives me debugging error: Class File Editor: Source not found
This is code of GoogleMaps
fragment:
public class GoogleMaps extends Fragment{
private GoogleMap googleMap;
double latitude = 46.514249;
double longitude = 15.080183;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View myFragmentView = inflater.inflate(R.layout.maps_layout, container, false);
try {
// Loading map
initilizeMap();
} catch (Exception e) {
Log.e("ERROR", "ERROR IN CODE: " + e.toString());
e.printStackTrace();
}
return myFragmentView;
}
private void initilizeMap() {
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
googleMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)));
CameraPosition cameraPosition = new CameraPosition.Builder().target(
new LatLng(latitude, longitude)).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
// check if map is created successfully or not
if (googleMap == null) {
Toast.makeText(getActivity(),
"Sorry! unable to create maps", Toast.LENGTH_SHORT)
.show();
}
}
}
}
Any help will be appreciated.
EDIT:
If I wasn't specific enough. It works when I load fragment
once (for the first time) but it doesn't work when I try to load it again (second time).
EDIT v2:
I actually found solution myself.
All I had to do was to add OnDestroyView
method:
public void onDestroyView()
{
super.onDestroyView();
Fragment fragment = (getFragmentManager().findFragmentById(R.id.map));
FragmentTransaction ft = getActivity().getFragmentManager().beginTransaction();
ft.remove(fragment);
ft.commit();
}
Thanks anyway.
Have a look at my implementation that works just fine and also dose some checking on the device before trying to diplay the map like if the Google play Services are installed. Maybe it will help you. I am using a simple FragmentActivity and inflating a layout containing a SupportedMapFragment.
Here's the code:
And the corresponding layout: