I want to show the current position in google maps with a marker inside a Fragment class. The map is already shown, but I get a NullpointerException, when I initialize the MapFragment.
I tried it with this initialization:
MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
This is the onMapReady() function:
#Override
public void onMapReady(GoogleMap googleMap) {
this.googlemap_global = googleMap;
googlemap_global.setMyLocationEnabled(true);
googlemap_global.setTrafficEnabled(true);
googlemap_global.setIndoorEnabled(true);
googlemap_global.setBuildingsEnabled(true);
googlemap_global.getUiSettings().setZoomControlsEnabled(true);
}
And this is the layout file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".GPSTracker2" >
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="400dp"
class="com.google.android.gms.maps.MapFragment" />
<Button
android:id="#+id/gps_service_start_stop_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="GPS Service starten"/>
Here I set the Markers:
LatLng latlng = new LatLng(latitude_global,longitude_global );
if(googlemap_global != null){
Marker aktueller_standort = googlemap_global.addMarker(new MarkerOptions().position(latlng).title("Standort"));
googlemap_global.moveCamera(CameraUpdateFactory.newLatLngZoom(latlng, 15));
// Zoom in, animating the camera.
googlemap_global.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);
}
Here is the logcat output:
java.lang.NullPointerException: Attempt to invoke virtual method
'android.app.Fragment android.app.FragmentManager.findFragmentById(int)' on a null object reference
at com.gpstracker.viktor.gpstracker2.Home_Fragment.<init>(Home_Fragment.java:82)
at com.gpstracker.viktor.gpstracker2.GPSTracker2.selectItemFromDrawer(GPSTracker2.java:105)
at com.gpstracker.viktor.gpstracker2.GPSTracker2.access$000(GPSTracker2.java:28)
at com.gpstracker.viktor.gpstracker2.GPSTracker2$1.onItemClick(GPSTracker2.java:67)
at android.widget.AdapterView.performItemClick(AdapterView.java:310)
at android.widget.AbsListView.performItemClick(AbsListView.java:1145)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:3066)
at android.widget.AbsListView$3.run(AbsListView.java:3903)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5461)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Thanks for helping.
Your XML File
<FrameLayout
android:id="#+id/mapContainer"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
Java file code
FrameLayout mapContainer = (FrameLayout) findViewById(R.id.mapContainer);
//show map of 40% of screen
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT);
params.height = (int) ((float) dm.heightPixels * (float) 0.5);
mapContainer.setLayoutParams(params);
FragmentManager fm = getFragmentManager();
MapFragment mapFragment = MapFragment.newInstance();
fm.beginTransaction().replace(R.id.mapContainer, mapFragment).commit();
mapFragment.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
GoogleMap mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
addMarks(mMap);
Show marker on map
private void addMarks(GoogleMap googleMap) {
LatLngBounds.Builder builder = new LatLngBounds.Builder();
LatLng latLng = new LatLng(lat1, long1);
builder.include(latLng);
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title(currentLocation);
googleMap.addMarker(markerOptions);
}
Change this like below
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="400dp"
class="com.google.android.gms.maps.MapFragment" />
to
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="400dp"
class="com.google.android.gms.maps.SupportMapFragment" />
and
MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.map);
to
SupportMapFragment branchdetails_map =
(SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
Related
I have a MapActivity (The default by Android) and a MainActivity. And i call the MapActivity with an include like this at the MainActivity:
<include
android:id="#+id/mapa"
layout="#layout/activity_maps"/>
It shows me the map but not the markers anyone knows why? In the MapActivity i have this:
private GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap)
{
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
Thanks all!
Use this only dont call include layout it wont work properly
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.mapwithmarker.MapsMarkerActivity" />
I get the following error when I try to leave fragment which contains map (on back button press).
ERROR: mapInflater->Binary XML file line #7: Error inflating class fragment
Bellow is onCreate() method of fragment where the map is placed. And also there is a xml code of layout.
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
apiRequestManager = ApiRequestManager.getInstance();
fragmentHandler = FragmentHandlerActivityMain.getInstance(getActivity());
session = new SessionManager(App.getInstance().getApplicationContext());
((AppCompatActivity) getActivity()).getSupportActionBar().setTitle(getString(R.string.maps_fragment_toolbar_name));
Handler mainHandler = new Handler();
Runnable myRunnable = new Runnable() {
#Override
public void run() {
try {
SupportMapFragment maps = (SupportMapFragment) getChildFragmentManager()
.findFragmentById(R.id.mapView);
if (maps != null)
maps.getMapAsync(MapsFragment.this);
} catch (Exception ex) {
LogUtil.getInstance().add(LogUtil.ERROR,
TAG, "onCreateMaps", ex);
}
}
};
mainHandler.post(myRunnable);
}
Log is pointing on this layout on fragment (line 7).
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app1="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".salesman.fragments.MapsFragment">
<fragment
android:id="#+id/mapView"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true"/>
</FrameLayout>
You are trying to getChildFragmentManager() instade of getSupportFragmentManager().
Need to change In Java File :
1). You need to implements OnMapReadyCallback in Your Fragment.
2). Get SupportMapFragment from View.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
3). Overrid onMapReady(GoogleMap googlMap) Method.
#Override
public void onMapReady(GoogleMap googleMap) {
// Add a marker in Sydney, Australia,
LatLng sydney = new LatLng(-33.852, 151.211);
googleMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
// and move the map's camera to the same location.
googleMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
In XML File :-
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app1="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".salesman.fragments.MapsFragment">
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</FrameLayout>
Please check the updated answer as per below comment:
Now try to set MapView insted of fragment because if you use fragment inside fragment it creates lot of issues.
Need to change in JAVA Code : // Initialize GoogleMap myMap; MapView mMapView;
// OnCreateView Method MapsInitializer.initialize(this.getActivity()); mMapView = (MapView) rootView.findViewById(R.id.map); mMapView.onCreate(savedInstanceState); mMapView.getMapAsync(this);
#Override public void onPause() { super.onPause(); mMapView.onPause(); }
#Override public void onPause() { super.onPause(); mMapView.onPause(); }
#Overridepublic void onResume() { super.onResume(); mMapView.onResume(); }
Need to change in XML File :
<com.google.android.gms.maps.MapView android:id="#+id/map" android:layout_width="match_parent" android:layout_height="match_parent" />
I need to add two buttons that overlays on the google map such that each click shows a different set of markers on the map. Is this achievable or do I need to change the approach?
My Fragment code:
public class HomeFragment extends Fragment {
public HomeFragment(){}
static final LatLng VELACHERY = new LatLng(12.9758, 80.2205);
static final LatLng TAMBARAM = new LatLng(12.9300, 80.1100);
private GoogleMap map;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
//creating Markers
Marker hamburg = map.addMarker(new MarkerOptions().position(VELACHERY)
.title("Velachery"));
Marker kiel = map.addMarker(new MarkerOptions()
.position(TAMBARAM)
.title("Volunteer")
.snippet("I am safe")
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.ic_launcher)));
// Move the camera instantly to hamburg with a zoom of 15.
map.moveCamera(CameraUpdateFactory.newLatLngZoom(VELACHERY, 15));
// Zoom in, animating the camera.
map.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);
//map.setOnMarkerClickListener(listener)
return rootView;
}
public void onDestroyView() {
super.onDestroyView();
if (map != null) {
getFragmentManager()
.beginTransaction()
.remove(getFragmentManager().findFragmentById(R.id.map))
.commit();
}
}
}
My Fragment layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".MainActivity" >
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.MapFragment" />
</RelativeLayout>
Yes, it's possible.
You could use a MapView or MapFragment-SupportMapFragment in a FrameLayout with the layout that contains your two buttons
Use OnMapReadyCallback to get the Google Map instance getMap is deprecated - look for getMapAsync(OnMapReadyCallback)
Handle View.OnClickListener for buttons
Each time a button is pressed call GoogleMap.clear(); then add the markers you need to display for the button that is pressed
Layout
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.gms.maps.MapView
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom">
<Button
android:id="#+id/buttonA"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button A"/>
<Button
android:id="#+id/buttonB"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button B"/>
</LinearLayout>
</FrameLayout>
Code
buttonA = (Button)findViewById(R.id.buttonA);
buttonA.setOnClickListener(this);
buttonB = (Button)findViewById(R.id.buttonB);
buttonB.setOnClickListener(this);
mapView = (MapView)findViewById(R.id.map);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
Implement OnMapReadyCallback.onMapReady
#Override
public void onMapReady( GoogleMap googleMap )
{
this.googleMap = googleMap;
//Do any other setup you would like here
}
In my project im trying to implementthis solution for managing a map in a dynamic added fragment.
public class MapFragment extends Fragment {
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
static final LatLng KIEL = new LatLng(53.551, 9.993);
private GoogleMap map;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v =inflater.inflate(R.layout.fragment_map, container, false);
map = ((SupportMapFragment) getFragmentManager().findFragmentById(R.id.map))
.getMap();
Marker kiel = map.addMarker(new MarkerOptions()
.position(KIEL)
.title("Kiel")
.snippet("Kiel is cool")
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.ic_arrow)));
// Move the camera instantly to hamburg with a zoom of 15.
map.moveCamera(CameraUpdateFactory.newLatLngZoom(KIEL, 15));
// Zoom in, animating the camera.
map.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);
return v;
}
}
My view:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/ColorBackground"
tools:context="com.example.sven.questy.GameFragments.MapFragment">
<fragment
android:layout_width="fill_parent"
android:layout_height="fill_parent" android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment" />
</RelativeLayout>
WHen i run the app i get a nullpointer exception on:
map = ((SupportMapFragment) getFragmentManager().findFragmentById(R.id.map))
.getMap();
The id of the map = map ( android:id="#+id/map").
Why the nullpointer?
Since you are using nested fragments, you should use getChildFragmentManager()
SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
And I recommend you to use getMapAsync method, because getMap is deprecated
mapFragment.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
setupMap(googleMap);
}
});
You need to use findViewById on the view you get, not using the fragment manager. The map is attached to the view
View v =inflater.inflate(R.layout.fragment_map, container, false);
map = v.findViewById(R.id.map))
.getMap();
I have a Google Maps Activity. suddently it is shutting down because getMap() (java null pointer exeption) doesn't seem to work. I reinstalled some older apks that worked fine and but yet these are shutting down to. So it has to be something on the device or so, what can be the reason?
private GoogleMap googleMap;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
if(googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
}
Here is the xml file
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<fragment
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/map"
android:name="com.google.android.gms.maps.MapFragment"/>
Logcat:
java.lang.RuntimeException: Unable to start activity ComponentInfo{de.mareike.cityexplorer/de.mareike.cityexplorer.MainActivity}: java.lang.NullPointerException
Caused by: java.lang.NullPointerException
at com.google.l.a.ce.a(Unknown Source)
at com.google.maps.api.android.lib6.d.eg.<init>(Unknown Source)
at com.google.maps.api.android.lib6.d.ef.a(Unknown Source)
at com.google.maps.api.android.lib6.d.aq.<init>(Unknown Source)
at com.google.maps.api.android.lib6.d.ft.a(Unknown Source)
at com.google.android.gms.maps.internal.l.onTransact(SourceFile:167)
at android.os.Binder.transact(Binder.java:380)
at com.google.android.gms.maps.internal.IGoogleMapDelegate$zza$zza.addMarker(Unknown Source)
at com.google.android.gms.maps.GoogleMap.addMarker(Unknown Source)
at de.mareike.cityexplorer.MainActivity.onCreate(MainActivity.java:88)
According to here, the getMap() method is deprecated and you need to use getMapAsync(OnMapReadyCallback) instead.
Sample code:
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap map) {
// Add a marker in Sydney, Australia, and move the camera.
LatLng sydney = new LatLng(-34, 151);
map.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
map.moveCamera(CameraUpdateFactory.newLatLngZoom(sydney, 10));
}
}
and the activity_main.xml:
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/map"
tools:context=".MapsActivity"
android:name="com.google.android.gms.maps.SupportMapFragment"/>
For more details, please refer official doc here.
Check your layout activity_main should contains fragment having id map
<fragment
android:id="#+id/map"
android:name="com.google.android.gms.maps.MapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />