I want to have a MapView in a Fragment. It seems simple... still I don't get it !
I get this error when launching the application :
java.lang.NullPointerException: Attempt to invoke interface method 'void maps.ad.y.v()' on a null object reference
I have an activity with a ViewPager : MainActivity
public class MainActivity extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
//...onCreate(), etc
public class SectionsPagerAdapter extends FragmentPagerAdapter {
//...
@Override
public Fragment getItem(int position) {
if (position == 0) {
return ClassicFragment.newInstance(position + 1);
// no problem with this one
} else if (position == 1) {
return MyMapFragment.newInstance(position + 1);
// here is my problem
}
}
}
}
And 2 fragment. (one simple, and one with a Map) The Fragment I don't manage to make properly : MyMapFragment
public class MyMapFragment extends SupportMapFragment implements OnMapReadyCallback {
View rootView;
private MapView mapView;
private GoogleMap googleMap;
public MyMapFragment() {
}
public static MyMapFragment newInstance(int sectionNumber) {
MyMapFragment fragment = new MyMapFragment();
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_map, container, false);
return rootView;
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
mapView = (MapView) rootView.findViewById(R.id.map);
mapView.onCreate(savedInstanceState);
mapView.onResume();
mapView.getMapAsync(this);//when you already implement OnMapReadyCallback in your fragment
}
@Override
public void onMapReady(GoogleMap map) {
googleMap = map;
}
}
Finally, here is the xml (fragment_map.xml) for the MyMapFragment.
<LinearLayout 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">
<com.google.android.gms.maps.MapView
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
Any idea what I'm doing wrong ?
I found 2 solutions :
Solution 1:
Change SupportMapFragment to Fragment.
Solution 2: (I chose this one)
Add this call in the MyMapFragment.