How to display Google Map in fragment? - android

I have a layout with ActionBar.NAVIGATION_MODE_TABS. The first tab is to display the results in listview and the second in a map. Everything worked great until I have upgraded to the latest version of Google Play Services lib.
Here the fragment used to display the map:
public class PlaceMapFragment extends Fragment {
MapView mapView;
GoogleMap map;
ResultsListener mCallback;
List<Place> places;
private HashMap<String, Place> placeMarker = new HashMap<String, Place>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
places = mCallback.getPlaces();
View rootView = inflater.inflate(R.layout.mapview, container, false);
mapView = (MapView) rootView.findViewById(R.id.mapview);
mapView.onCreate(savedInstanceState);
map = mapView.getMap();
setUpMap();
return rootView;
}
private void setUpMap() {
map.getUiSettings().setMyLocationButtonEnabled(true);
map.setMyLocationEnabled(true);
/*
try {
MapsInitializer.initialize(this.getActivity());
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
*/
// add markers
}
#Override
public void onResume() {
mapView.onResume();
super.onResume();
setUpMap();
}
#Override
public void onPause() {
mapView.onPause();
super.onPause();
}
#Override
public void onDestroy() {
mapView.onDestroy();
super.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
public interface ResultsListener {
public List<Place> getPlaces();
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
mCallback = (ResultsListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement ResultsListener");
}
}
}
I get these errors:
04-05 03:58:22.040: E/AndroidRuntime(661): FATAL EXCEPTION: main
04-05 03:58:22.040: E/AndroidRuntime(661): java.lang.NullPointerException
04-05 03:58:22.040: E/AndroidRuntime(661): at com.tomsyweb.mapslee.fragments.PlaceMapFragment.setUpMap(PlaceMapFragment.java:54)
04-05 03:58:22.040: E/AndroidRuntime(661): at com.tomsyweb.mapslee.fragments.PlaceMapFragment.onCreateView(PlaceMapFragment.java:48)
I have commented the MapsInitializer.initialize(this.getActivity()); part because GooglePlayServicesNotAvailableException gives error.
mapview.xml
<com.google.android.gms.maps.MapView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/mapview"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
My code is taken from Getting Google Map Fragment in onCreateView using ActionBar tabs

Your map may be null if the device doesn't have the latest version of Maps installed, or perhaps for other reasons. Trying to create it may even prompt the user to start a different activity to update their device. So it's recommended to create an initMap() method like this, and call it in your onCreate(...) and onResume():
private void initMap() {
if(map == null) {
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
if(map != null) {
// set up map
}
}
}

Related

Android Google Map v2 in Navigation Drawer in onCreateView()

I'm having an issue with my Android app. I'm using navigation drawer with onCreateView() inside of a PlaceholderFragment like this:
// Google Map
private GoogleMap map;
private final LatLng LOCATION_DEPAUW = new LatLng(39.640343, -86.860687);
public static class PlaceholderFragment extends Fragment {
/**
* Returns a new instance of this fragment for the given section number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#SuppressWarnings("unused")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = null;
...
else if(mTitle.equals("Map")){
Log.d("Map", "Worked");
rootView = inflater.inflate(R.layout.google_map, container, false);
try {
if (map == null) {
SupportMapFragment fm = (SupportMapFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.map);
map = fm.getMap();
}
// Needs to call MapsInitializer before doing any CameraUpdateFactory calls
try {
MapsInitializer.initialize(this.getActivity());
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(LOCATION_DEPAUW, 15);
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
// Enabling MyLocation Layer of Google Map
map.setMyLocationEnabled(true);
map.getUiSettings().setZoomGesturesEnabled(true);
map.getUiSettings().setCompassEnabled(true);
map.getUiSettings().setRotateGesturesEnabled(true);
map.animateCamera(update);
/*
* for different colors:
* googlemap.addMarker(new MarkerOptions().position(new LatLng( 65.07213,-2.109375)).title("This is my title").snippet("and snippet").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE)));
*
* .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE) is the key. change the HUE_ORANGE to anything that is available
*
*/
} catch (Exception e) {
Toast.makeText(getActivity(), e.toString(), Toast.LENGTH_LONG).show();
}
}
I have already imported everything correctly and the map initializes correctly on the first view. The problem is when I navigate to another fragment and then go back to this map fragment, my app crashes. I've tried to use an eclipse emulator but couldnt get it configured correctly. Does anyone know a way to handle the life cycle of a map inside a placeholderfragment? Thanks!
So after a lot of research, I found out someone manage to handle this well.
Check out this github repository:
https://gist.github.com/joshdholtz/4522551
MapView mapView;
GoogleMap map;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.some_layout, container, false);
// Gets the MapView from the XML layout and creates it
mapView = (MapView) v.findViewById(R.id.mapview);
mapView.onCreate(savedInstanceState);
// Gets to GoogleMap from the MapView and does initialization stuff
map = mapView.getMap();
map.getUiSettings().setMyLocationButtonEnabled(false);
map.setMyLocationEnabled(true);
// Needs to call MapsInitializer before doing any CameraUpdateFactory calls
try {
MapsInitializer.initialize(this.getActivity());
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
// Updates the location and zoom of the MapView
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(43.1, -87.9), 10);
map.animateCamera(cameraUpdate);
return v;
}
#Override
public void onResume() {
mapView.onResume();
super.onResume();
}
#Override
public void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
initially though, I had issues cause I had multiple fragments to switch between, so i did this in mine:
public void onResume() {
try{
super.onResume();
mapView.onResume();
}catch(NullPointerException e){
Log.d("onResume", "NullPointerException: " + e);
}
}
#Override
public void onDestroy() {
try{
super.onDestroy();
mapView.onDestroy();
}catch(NullPointerException e){
Log.d("onDestroy", "NullPointerException: " + e);
}
}
#Override
public void onLowMemory() {
try{
super.onLowMemory();
mapView.onLowMemory();
}catch(NullPointerException e){
Log.d("onLowMemory", "NullPointerException: " + e);
}
}

java.lang.NullPointerException: CameraUpdateFactory is not initialized logcat exception

I'm working with Google Maps. I am able to successfully create and can show a Google Map. Now I want to add CameraUpdate(latitude, longitude). I googled and I found some source code but I'm getting a NullPointerException.
The LogCat error message is:
java.lang.NullPointerException: CameraUpdateFactory is not initialized
This is my source. What am I doing wrong?
public class StradaContact extends Fragment {
public final static String TAG = StradaContact.class.getSimpleName();
private MapView mMapView;
private GoogleMap mMap;
private Bundle mBundle;
double longitude = 44.79299800000001, latitude = 41.709981;
public StradaContact() {
}
public static StradaContact newInstance() {
return new StradaContact();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.strada_contact, container,false);
mMapView = (MapView) rootView.findViewById(R.id.pointMap);
mMapView.onCreate(mBundle);
setUpMapIfNeeded(rootView);
return rootView;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mBundle = savedInstanceState;
}
private void setUpMapIfNeeded(View inflatedView) {
if (mMap == null) {
mMap = ((MapView) inflatedView.findViewById(R.id.pointMap)).getMap();
if (mMap != null) {
CameraUpdate center = CameraUpdateFactory.newLatLng(new LatLng(latitude, longitude));
CameraUpdate zoom = CameraUpdateFactory.zoomTo(15);
mMap.moveCamera(center);
mMap.animateCamera(zoom);
}
}
}
#Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mMapView.onPause();
}
#Override
public void onDestroy() {
mMapView.onDestroy();
super.onDestroy();
}
}
<com.google.android.gms.maps.MapView
android:id="#+id/pointMap"
android:name="com.google.android.gms.maps.MapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.MapFragment" />
Try this in "onCreate":
try {
MapsInitializer.initialize(this);
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
Try with following method initialize google map api before using
MapsInitializer.initialize(getActivity());

android MapFragment doesn't show on replace

I have two FrameLayout in an activity, I just replace fragments inside those FrameLayout.
It works great with everyfragment BUT the one containing the MapFragment for the GoogleMap.
When I first launch the app it works and I see the map (everything works) but when I replace the fragment and replace it back I just get a blank space like nothing is loaded.
public class MapFragment extends CustomFragment {
private GoogleMap mMap;
private Marker currentMarker;
private OnFragmentInteractionListener mListener;
public static final String ID = "MAP_FRAGMENT";
private static View view;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = null;
try {
view = inflater.inflate(R.layout.fragment_map, container, false);
} catch (InflateException e) {
Log.d("","");
}finally{
setUpMapIfNeeded();
if(view!=null)this.view=view;
return this.view;
}
}
#Override
public void onDestroyView() {
super.onDestroyView();
Fragment f = getFragmentManager().findFragmentById(R.id.map);
if (f != null)getActivity().getFragmentManager().beginTransaction().remove(f).commit();
mMap=null;
currentMarker=null;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
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 = ((com.google.android.gms.maps.MapFragment)getFragmentManager().findFragmentById(R.id.map)).getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
private void setUpMap() {
}
#Override
public void onPause() {
super.onPause();
}
#Override
public void update(FragmentMessage message) {
if(mMap!=null) {
Location loc = (Location) message.getMessages()[0];
if (currentMarker != null)
currentMarker.remove();
currentMarker = mMap.addMarker(new MarkerOptions().position(new LatLng(loc.getLatitude(), loc.getLongitude())).title("Marker"));
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(loc.getLatitude(), loc.getLongitude())) // Sets the center of the map to Mountain View
.zoom(15) // Sets the zoom
.build(); // Creates a CameraPosition from the builder
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
}
}
The mMap is never null, so the MapFragment is working I guess but I don't get anything on the screen (see screenshots below).
Does anyone have an idea ? I really don't know what is wrong.

Google Maps only shows one marker Android

I've the next problem, I'm trying to show some markers in a Google Map, but only show the first marker, not the others. It don't throw any exception, but only shows the first marker (the phone position).
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
context = getActivity().getApplicationContext();
v = inflater.inflate(R.layout.fragment_map, container, false);
Bundle b = getArguments();
receiveExtraData(b);
MapsInitializer.initialize(getActivity());
mMapView = (MapView) v.findViewById(R.id.map);
mMapView.onCreate(mBundle);
setUpMapIfNeeded(v);
return v;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
listener = (FragmentsListener) activity;
} catch (ClassCastException e) {}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mBundle = savedInstanceState;
}
private void setUpMapIfNeeded(View inflatedView) {
if (mMap == null) {
mMap = ((MapView) inflatedView.findViewById(R.id.map)).getMap();
if (mMap != null) {
setUpMap();
}
}
}
private void setUpMap() {
GPSPoint point = new GPSPoint(context);
LatLng latLng = point.getCurrentPositionLatLng();
MarkerOptions phoneMarker = new MarkerOptions().position(latLng).title("Marker");
mMap.addMarker(phoneMarker);
phoneMarker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
CameraPosition cameraPosition = new CameraPosition.Builder().target(latLng).zoom(20).build();
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
addDevicesMarkers(connectedDevices);
}
#Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mMapView.onPause();
}
#Override
public void onDestroy() {
mMapView.onDestroy();
super.onDestroy();
}
private void receiveExtraData(Bundle b){
connectedDevices = b.getParcelableArrayList(BundlesKeys.BLUETOOTH_DEVICES_ARRAY);
}
private void getDevicePosition(BluetoothDevice bDevice){
listener.getDeviceLocation(bDevice);
}
private void addDevicesMarkers(ArrayList<BluetoothDevice> list){
if (!list.isEmpty()){
BluetoothDevice device = list.get(0);
getDevicePosition(device);
}
}
public void addMarker(LatLng pos){
MarkerOptions deviceMarker = new MarkerOptions().position(pos).title("Device");
mMap.addMarker(deviceMarker);
}
Somebody knows the fix?? Somebody knows how to program a listener for devices location events?
You just have to use mMap.addMarker() as many times as the number of markers that you want to show. If you are using it only one time, like you are doing inside setUpMap(), you will only see one marker.
Don't forget to change your MarkerOptions attributes for each marker.

Android Google Maps : Map View initialization

I am trying to display a simple map in my Android application, using the MapView class.
I use the following onCreate method in my activity :
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
MapsInitializer.initialize(this);
} catch (GooglePlayServicesNotAvailableException e) {
Log.e("Address Map", "Could not initialize google play", e);
}
MapView mapView = new MapView(this);
CameraUpdate camPos = CameraUpdateFactory.newLatLng(new LatLng(11.562276,104.920292));
mapView.getMap().moveCamera(camPos);
setContentView(mapView);
}
I have a NullPointerException, because the method mapView.getMap() returns null.
Don't understand why, Google play services are apparently present and initialized.
Could not get MapView to work, I finally ended using the class SupportMapFragment.
For those that it may help, here is the complete code of my activity :
public class AddressMap extends android.support.v4.app.FragmentActivity {
private final static int FRAGMENT_ID = 0x101;
private GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.HORIZONTAL);
layout.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
SupportMapFragment fragment = SupportMapFragment.newInstance();
layout.setId(0x101);
{
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(FRAGMENT_ID, fragment);
fragmentTransaction.commit();
}
setContentView(layout);
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
if (mMap == null) {
mMap = ((SupportMapFragment) getSupportFragmentManager()
.findFragmentById(FRAGMENT_ID)).getMap();
if (mMap != null) {
mMap.moveCamera(
CameraUpdateFactory.newLatLngZoom(new LatLng(11.562276, 104.920292), 10));
}
}
}
}
Also, mapView.onCreate() must be called.
You are trying to access Google Maps Android v1 Api which is now deprecated, please use Google Map Android Api v2
I used it like this and it worked, this is with the new api:
compile 'com.google.android.gms:play-services-maps:10.2.6'
public class MapViewFragment extends Fragment{
public static final String TAG = MapViewFragment.class.getSimpleName();
MapView mapView;
GoogleMap map;
static MapViewFragment instance;
public static MapViewFragment newInstance(){
if(instance == null){
instance = new MapViewFragment();
return instance;
}else{
return instance;
}
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
Log.i(TAG, "onCreateView: " );
View view = inflater.inflate(R.layout.map_view_fragment, container, false);
mapView = (MapView) view.findViewById(R.id.mvMap);
if(mapView != null){
mapView.onCreate(null); //Don't forget to call onCreate after get the mapView!
mapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
map = googleMap;
//Do what you want with the map!!
}
});
MapsInitializer.initialize(this.getActivity());
}else{
Log.i(TAG, "onCreateView: mapView is null");
}
return view;
}
#Override
public void onResume() {
mapView.onResume();
super.onResume();
}
#Override
public void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
}
And here is my layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.gms.maps.MapView
android:id="#+id/mvMap"
android:layout_width="match_parent"
android:layout_height="match_parent">
</com.google.android.gms.maps.MapView>
</LinearLayout>

Categories

Resources