SupportMapFragment.getMap () для ссылки на нулевой объект

Попробовав почти все, я не могу получить getmap, не вытаскивая ссылку на нулевой объект. Я пытаюсь раздуть фрагмент карты google в фрагмент, но каждый раз, когда я это делаю, я всегда сохраняю нулевой объект getmap.

Вот мой код

На данный момент я отчаянно нуждаюсь в помощи, я пробовал практически все.


java.lang.NullPointerException: Attempt to invoke virtual method '' on a null object reference at com.gnumbu.errolgreen.importedapplication.ViewMapFragment.onViewCreated( at at at at at at at at at at android.view.View.measure( at android.view.ViewGroup.measureChildWithMargins( at android.widget.FrameLayout.onMeasure( at android.view.View.measure( at android.view.ViewGroup.measureChildWithMargins( at at android.view.View.measure( at android.view.ViewGroup.measureChildWithMargins( at android.widget.FrameLayout.onMeasure( at android.view.View.measure( at android.view.ViewGroup.measureChildWithMargins( at android.widget.LinearLayout.measureChildBeforeLayout( at android.widget.LinearLayout.measureVertical( at android.widget.LinearLayout.onMeasure( at android.view.View.measure( at android.view.ViewGroup.measureChildWithMargins( at android.widget.FrameLayout.onMeasure( at$DecorView.onMeasure( at android.view.View.measure( at android.view.ViewRootImpl.performMeasure( at android.view.ViewRootImpl.measureHierarchy( at android.view.ViewRootImpl.performTraversals( at android.view.ViewRootImpl.doTraversal( at android.view.ViewRootImpl$ at android.view.Choreographer$ at android.view.Choreographer.doCallbacks( at android.view.Choreographer.doFrame( at android.view.Choreographer$ at android.os.Handler.handleCallback( at android.os.Handler.dispatchMessage( at android.os.Looper.loop( at at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke( at$ at 

Класс фрагмента java

 public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { if (container == null) { return null; } view = (RelativeLayout) inflater.inflate(R.layout.fragmentmenu_layout, container, false); // Passing harcoded values for latitude & longitude. Please change as per your need. This is just used to drop a Marker on the Map latitude = 26.78; longitude = 72.56; ; // For setting up the MapFragment return view; } /***** Sets up the map if it is possible to do so *****/ public static 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 = ((SupportMapFragment) SectionsPagerAdapter.fragmentManager .findFragmentById(; // Check if we were successful in obtaining the map. if (mMap != null) setUpMap(); } } /** * This is where we can add markers or lines, add listeners or move the * camera. * <p> * This should only be called once and when we are sure that {@link #mMap} * is not null. */ private static void setUpMap() { // For showing a move to my loction button mMap.setMyLocationEnabled(true); // For dropping a marker at a point on the Map mMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title("My Home").snippet("Home Address")); // For zooming automatically to the Dropped PIN Location mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude), 12.0f)); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { // TODO Auto-generated method stub if (mMap != null) setUpMap(); if (mMap == null) { // Try to obtain the map from the SupportMapFragment. mMap = ((SupportMapFragment) MainActivity.fragmentManager .findFragmentById(; // getMap is deprecated // Check if we were successful in obtaining the map. if (mMap != null) setUpMap(); getAllFeaturedItems(); captureMapScreen(); } } @Override public void onStart() { super.onStart(); } @Override public void onResume() { super.onResume(); setUpMapIfNeeded(); } @Override public void onPause() { super.onPause(); } @Override public void onStop() { super.onStop(); } @Override public void onLowMemory() { super.onLowMemory(); } /**** The mapfragment's id must be removed from the FragmentManager **** or else if the same it is passed on the next time then **** app will crash ****/ @Override public void onDestroyView() { super.onDestroyView(); if (mMap != null) { MainActivity.fragmentManager.beginTransaction() .remove(MainActivity.fragmentManager.findFragmentById(; mMap = null; } } @Override public void onDestroy() { super.onDestroy(); } 


  <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" android:translationZ="5dp" > <ListView android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/listViewMenu" android:layout_gravity="center_horizontal" android:dividerHeight="1sp" android:translationZ="5dp" android:divider="@color/background_default" android:background="@color/background_white" android:clickable="true" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_below="@+id/screenShotMapView" /> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/screenShotMapView" android:layout_alignParentTop="true" android:maxWidth="50dp" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_alignParentRight="true" android:layout_alignParentEnd="true" android:adjustViewBounds="true" android:translationZ="5dp" /> <fragment class="" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/mapView" android:layout_alignParentTop="true" android:layout_alignParentRight="true" android:layout_alignParentEnd="true" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:adjustViewBounds="true" android:longClickable="false" android:visibility="visible" android:maxHeight="50dp" android:maxWidth="50dp" /> </RelativeLayout>

 public static FragmentManager fragmentManager; @Override protected void onCreate(Bundle savedInstanceState) { // setTheme(; super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initialising the object of the FragmentManager. Here I'm passing getSupportFragmentManager(). You can pass getFragmentManager() if you are coding for Android 3.0 or above. // final ActionBar actionBar = getSupportActionBar(); buildGoogleApiClient(); // actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); // actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); mImageBitmap = null; // Create the adapter that will return a fragment for each section/page mSectionsPagerAdapter = new SectionsPagerAdapter( this.getBaseContext(), getSupportFragmentManager()); fragmentManager = getSupportFragmentManager(); // Set up the ViewPager with the sections adapter. mViewPager = (ViewPager) findViewById(; mViewPager.setAdapter(mSectionsPagerAdapter); mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() { @Override public void onPageSelected(int position) { // actionBar.setSelectedNavigationItem(position); } }); // For each of the sections in the app, add a tab to the action bar. /* for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) { // Create a tab with text corresponding to the page title defined by // the adapter. Also specify this Activity object, which implements // the TabListener interface, as the callback (listener) for when // this tab is selected. if (i == 0) { actionBar.addTab( actionBar.newTab() .setIcon(R.drawable.ic_action_view_as_list) // .setText(mSectionsPagerAdapter.getPageTitle(i)) .setTabListener(this) ); } if (i == 1) { actionBar.addTab( actionBar.newTab() .setIcon(R.drawable.ic_action_web_site_dark) // .setText(mSectionsPagerAdapter.getPageTitle(i)) .setTabListener(this) ); } } */ mAlbumStorageDirFactory = new BaseAlbumDirFactory(); Intent intent = new Intent(this, SplashScreen.class); startActivity(intent); } 

Solutions Collecting From Web of "SupportMapFragment.getMap () для ссылки на нулевой объект"

Не слишком уверен, почему я так сильно опустился, но я решил проблему.

Эта линия

 mMap = ((SupportMapFragment) MainActivity.fragmentManager .findFragmentById(; 

Необходимо было изменить на

  mMap = ((SupportMapFragment) getChildFragmentManager() .findFragmentById(; 

Android: name = должно быть изменено на "", т.е.


 <fragment android:name="" android:layout_width="match_parent" android:layout_height="match_parent"/> 


 <fragment android:name="" android:layout_width="match_parent" android:layout_height="match_parent"/> 

Проблема в том, что вы пытаетесь получить карту из SupportMapFragment но вы используете другой тип MapFragment который четко просматривается в xml


Должен быть


Чтобы вы могли инициализировать тип SupportMapFragment из вашего кода

Я изменил getMap() на getMapAsync(OnMapReadyCallback) и он сработал.

Источник: SupportMapFragment