使用SupportMapFragment getMap()时获取java.lang.NullPointerException;在片段中

时间:2014-10-23 19:21:01

标签: android google-maps nullpointerexception fragment supportmapfragment

今天,我的Eclipse崩溃了。因此,我重新创建了我的项目。

我没有更改代码,但它无法正常工作。

问题是当我使用SupportMapFragment getMap()函数时,我得到了一个

显示java.lang.NullPointerException。

很奇怪,因为它在我重新创建项目之前工作正常。代码如下所示:

public class MapFragment extends Fragment {

private static GoogleMap mMap;
private LocationManager locationManager;
private LocationListener locationListener;
private String mUserName;
private final static int DAY = 0;
private final static int MONTH = 1;
private final static int YEAR = 2;
private long timeFrom, timeTo, now;
private Button btnTimeChanger;
private int postion = 2;
private View view;

public View onCreateView(LayoutInflater inflater, ViewGroup container,          Bundle savedInstanceState) {

             LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT,
                                 LayoutParams.MATCH_PARENT);
             FrameLayout fl = new FrameLayout(getActivity());
             fl.setLayoutParams(params);
             DisplayMetrics dm = getResources().getDisplayMetrics();
             final int margin = (int) TypedValue.applyDimension(
                             TypedValue.COMPLEX_UNIT_DIP, 8, dm);

             view = inflater.inflate(R.layout.mapdisplay, container, false);

             int status = GooglePlayServicesUtil
                          .isGooglePlayServicesAvailable(getActivity().getBaseContext());

             if (status != ConnectionResult.SUCCESS) { // Google Play Services are
                                                           // not available

             int requestCode = 10;
             Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status,
                    getActivity(), requestCode);
              dialog.show();

        } else { // Google Play Services are available

            view = initializeMap(view);
                    TextView v = new TextView(getActivity());
            params.setMargins(margin, margin, margin, margin);
            v.setLayoutParams(params);
            v.setGravity(Gravity.CENTER);
            v.setText("Google Map");
            v.setTextSize((int) TypedValue.applyDimension(
                   TypedValue.COMPLEX_UNIT_SP, 12, dm));
            fl.addView(view);
            fl.addView(v);
            return fl;
        }

    private View initializeMap(View v) {        // TODO Auto-generated method stub
                SupportMapFragment fm = (SupportMapFragment) getActivity()
                .getSupportFragmentManager().findFragmentById(R.id.google_map);
                // Getting GoogleMap object from the fragment
                mMap = fm.getMap();
                mMap.setMyLocationEnabled(true);

        RadioGroup rgViews = (RadioGroup) v.findViewById(R.id.rg_views);

        rgViews.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override           public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.rb_map) {
                    mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
                } else if (checkedId == R.id.rb_satellite) {
                    mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
                }           }       });

        btnTimeChanger = (Button) v.findViewById(R.id.btnTimechanger);      btnTimeChanger.setText("Time");         btnTimeChanger.setTextSize(12);         btnTimeChanger.setHeight(13);       btnTimeChanger.setWidth(20);


        return v;

    }

相应的MapFragment视图xml文件:

<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" >

  <RadioGroup
        android:id="@+id/rg_views"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:orientation="horizontal" >

        <RadioButton
            android:id="@+id/rb_map"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/str_rb_map"
            android:checked="true" />

        <RadioButton
            android:id="@+id/rb_satellite"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/str_rb_satellite" />


    </RadioGroup>


   <Button
        android:id="@+id/btnTimechanger"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

    <fragment 
        android:id="@+id/google_map"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/rg_views"
        class="com.google.android.gms.maps.SupportMapFragment" />



</RelativeLayout>

当我运行应用程序时,它会显示如下的异常:

10-23 21:09:32.426: D/AndroidRuntime(10159): Shutting down VM
10-23 21:09:32.426: W/dalvikvm(10159): threadid=1: thread exiting with uncaught exception         (group=0x4208ac08)
10-23 21:09:32.441: E/AndroidRuntime(10159): FATAL EXCEPTION: main
10-23 21:09:32.441: E/AndroidRuntime(10159): Process: com.facebook.biodatashare, PID: 10159
10-23 21:09:32.441: E/AndroidRuntime(10159): java.lang.NullPointerException
10-23 21:09:32.441: E/AndroidRuntime(10159):    at com.facebook.biodatashare.display.MapFragment.initializeMap(MapFragment.java:244)
10-23 21:09:32.441: E/AndroidRuntime(10159):    at com.facebook.biodatashare.display.MapFragment.onCreateView(MapFragment.java:93)
10-23 21:09:32.441: E/AndroidRuntime(10159):    at android.support.v4.app.Fragment.performCreateView(Fragment.java:1786)
10-23 21:09:32.441: E/AndroidRuntime(10159):    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:947)
10-23 21:09:32.441: E/AndroidRuntime(10159):    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1126)
10-23 21:09:32.441: E/AndroidRuntime(10159):    at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:739)
10-23 21:09:32.441: E/AndroidRuntime(10159):    at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1489)
10-23 21:09:32.441: E/AndroidRuntime(10159):    at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:486)
10-23 21:09:32.441: E/AndroidRuntime(10159):    at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
10-23 21:09:32.441: E/AndroidRuntime(10159):    at android.support.v4.view.ViewPager.populate(ViewPager.java:1073)
10-23 21:09:32.441: E/AndroidRuntime(10159):    at android.support.v4.view.ViewPager.populate(ViewPager.java:919)
10-23 21:09:32.441: E/AndroidRuntime(10159):    at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1441)
10-23 21:09:32.441: E/AndroidRuntime(10159):    at android.view.View.measure(View.java:17387)
10-23 21:09:32.441: E/AndroidRuntime(10159):    at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:719)
10-23 21:09:32.441: E/AndroidRuntime(10159):    at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:455)
10-23 21:09:32.441: E/AndroidRuntime(10159):    at android.view.View.measure(View.java:17387)
10-23 21:09:32.441: E/AndroidRuntime(10159):    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5352)
10-23 21:09:32.441: E/AndroidRuntime(10159):    at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
10-23 21:09:32.441: E/AndroidRuntime(10159):    at android.view.View.measure(View.java:17387)
10-23 21:09:32.441: E/AndroidRuntime(10159):    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5352)
10-23 21:09:32.441: E/AndroidRuntime(10159):    at com.android.internal.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:391)
10-23 21:09:32.441: E/AndroidRuntime(10159):    at android.view.View.measure(View.java:17387)
10-23 21:09:32.441: E/AndroidRuntime(10159):    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5352)
10-23 21:09:32.441: E/AndroidRuntime(10159):    at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
10-23 21:09:32.441: E/AndroidRuntime(10159):    at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2533)
10-23 21:09:32.441: E/AndroidRuntime(10159):    at android.view.View.measure(View.java:17387)
10-23 21:09:32.441: E/AndroidRuntime(10159):    at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2213)
10-23 21:09:32.441: E/AndroidRuntime(10159):    at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1350)
10-23 21:09:32.441: E/AndroidRuntime(10159):    at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1549)
10-23 21:09:32.441: E/AndroidRuntime(10159):    at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1234)
10-23 21:09:32.441: E/AndroidRuntime(10159):    at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6467)
10-23 21:09:32.441: E/AndroidRuntime(10159):    at android.view.Choreographer$CallbackRecord.run(Choreographer.java:803)
10-23 21:09:32.441: E/AndroidRuntime(10159):    at android.view.Choreographer.doCallbacks(Choreographer.java:603)
10-23 21:09:32.441: E/AndroidRuntime(10159):    at android.view.Choreographer.doFrame(Choreographer.java:573)
10-23 21:09:32.441: E/AndroidRuntime(10159):    at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:789)
10-23 21:09:32.441: E/AndroidRuntime(10159):    at android.os.Handler.handleCallback(Handler.java:733)
10-23 21:09:32.441: E/AndroidRuntime(10159):    at android.os.Handler.dispatchMessage(Handler.java:95)
10-23 21:09:32.441: E/AndroidRuntime(10159):    at android.os.Looper.loop(Looper.java:157)
10-23 21:09:32.441: E/AndroidRuntime(10159):    at android.app.ActivityThread.main(ActivityThread.java:5356)
10-23 21:09:32.441: E/AndroidRuntime(10159):    at java.lang.reflect.Method.invokeNative(Native Method)
10-23 21:09:32.441: E/AndroidRuntime(10159):    at java.lang.reflect.Method.invoke(Method.java:515)
10-23 21:09:32.441: E/AndroidRuntime(10159):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
10-23 21:09:32.441: E/AndroidRuntime(10159):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
10-23 21:09:32.441: E/AndroidRuntime(10159):    at dalvik.system.NativeStart.main(Native Method)
10-23 21:09:32.476: D/dalvikvm(10159): GC_FOR_ALLOC freed 1169K, 24% free 21999K/28880K, paused 31ms, total 31ms
10-23 21:09:32.486: D/REQUEST(10159): Processing DataRequest: com.google.maps.api.android.lib6.b.d@432a7518
10-23 21:09:32.486: D/REQUEST(10159): Processing DataRequest: com.google.maps.api.android.lib6.c.au@43296960
10-23 21:09:32.486: D/REQUEST(10159): DRD(1): 62|147, <1s, <1kb
10-23 21:09:32.486: D/REQUEST(10159): Close
10-23 21:09:32.486: D/USER_EVENTS(10159): Event: type=22, status: fb, data: 66
10-23 21:09:32.491: D/USER_EVENTS(10159): Event: type=22, status: lb, data: 67
10-23 21:09:32.491: D/USER_EVENTS(10159): Event: type=22, status: flbs, data: fb=66|lb=67|s=16

这是该项目的清单文件:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.facebook.biodatashare"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="19" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <uses-feature android:name="android.hardware.camera" />
    <uses-feature android:name="android.hardware.camera.autofocus" />

    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
    <!--
         The following two permissions are not required to use
                    Google Maps Android API v2, but are recommended.
    -->
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >

        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />
        <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="AIzaSyCq7IeRF5UsyGEsFhq_mL538oSLy4tsk20" />

        <activity
            android:name="com.yixian.biodatashare.LoginActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.facebook.LoginActivity"
            android:label="@string/app_name" >
        </activity>
        <activity
            android:name="com.yixian.biodatashare.DataSelectActivity"
            android:label="@string/app_name" >
        </activity>
        <activity
            android:name="com.yixian.biodatashare.TimeSelectionActivity"
            android:label="@string/app_name" >
        </activity>
        <activity
            android:name="com.facebook.biodatashare.display.DisplayActivity"
            android:icon="@drawable/ic_launcher"
            android:label="@string/app_name" >
        </activity>


        <meta-data
            android:name="com.facebook.sdk.ApplicationId"
            android:value="@string/app_id" />
    </application>

</manifest>

MapFragment来自FragmentActivity:我使用了下载的PagerSlidingTabStrip

来自https://github.com/astuetz/PagerSlidingTabStrip

public class DisplayActivity extends FragmentActivity {

        private MapFragment mapFragment;  

        /** 
         * MapFragment 
         */  
        private DataAnalysisFragment dataAnalysisFragment;  

        /** 
         * DataAnalysisFragment 
         */  


        /** 
         *  The instance of PagerSlidingTabStrip 
         */  
        private PagerSlidingTabStrip tabs;  

        /** 
         * Obtain the metrics of the screen 
         */  
        private DisplayMetrics dm;  




        @Override  
        protected void onCreate(Bundle savedInstanceState) {  
            super.onCreate(savedInstanceState);  
            setContentView(R.layout.display);  
            setOverflowShowingAlways();  
            dm = getResources().getDisplayMetrics();  
            ViewPager pager = (ViewPager) findViewById(R.id.pager);  
            tabs = (PagerSlidingTabStrip) findViewById(R.id.tabs);  
            pager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));  
            tabs.setViewPager(pager);  
            setTabsValue();  
        }  

        /** 
         * 对PagerSlidingTabStrip的各项属性进行赋值。 
         */  
        private void setTabsValue() {  

            tabs.setShouldExpand(true);  

            tabs.setDividerColor(Color.TRANSPARENT);  

            tabs.setUnderlineHeight((int) TypedValue.applyDimension(  
                    TypedValue.COMPLEX_UNIT_DIP, 1, dm));  

            tabs.setIndicatorHeight((int) TypedValue.applyDimension(  
                    TypedValue.COMPLEX_UNIT_DIP, 4, dm));  

            tabs.setTextSize((int) TypedValue.applyDimension(  
                    TypedValue.COMPLEX_UNIT_SP, 16, dm));  

            tabs.setIndicatorColor(Color.parseColor("#45c01a"));  

            tabs.setSelectedTextColor(Color.parseColor("#45c01a"));  

            tabs.setTabBackground(0);  
        }  

        public class MyPagerAdapter extends FragmentPagerAdapter {  

            public MyPagerAdapter(FragmentManager fm) {  
                super(fm);  
            }  

            private final String[] titles = { "Map", "Data Analysis"};  

            @Override  
            public CharSequence getPageTitle(int position) {  
                return titles[position];  
            }  

            @Override  
            public int getCount() {  
                return titles.length;  
            }  

            @Override  
            public Fragment getItem(int position) {  
                switch (position) {  
                case 0:  
                    if (mapFragment == null) {  
                        mapFragment = new MapFragment();  
                    }  
                    return mapFragment;  
                case 1:  
                    if (dataAnalysisFragment == null) {  
                        dataAnalysisFragment = new DataAnalysisFragment();  
                    }  
                    return dataAnalysisFragment;  

                default:  
                    return null;  
                }  
            }  

        }  


        public void showDialog()
        {
            final CharSequence[] items={"Map","Chart","Both of them"};
            AlertDialog.Builder builder=new AlertDialog.Builder(this);
            builder.setTitle("Which presentation will be shared on facebook?");
            builder.setPositiveButton("ok", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {



                }
            });

            builder.setSingleChoiceItems(items,-1, new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub


                    if("Red".equals(items[which]))
                    {

                    }
                    else if("Green".equals(items[which]))
                    {

                        }
                    else if("Blue".equals(items[which]))
                    {

                        }

                }
            });
            builder.show();

        }

    @Override  
    public boolean onCreateOptionsMenu(Menu menu) {  
        getMenuInflater().inflate(R.menu.main, menu);  
        return true;  

    }  



    @Override  
    public boolean onMenuOpened(int featureId, Menu menu) {  
        if (featureId == Window.FEATURE_ACTION_BAR && menu != null) {  
            if (menu.getClass().getSimpleName().equals("MenuBuilder")) {  
                try {  
                    Method m = menu.getClass().getDeclaredMethod(  
                            "setOptionalIconsVisible", Boolean.TYPE);  
                    m.setAccessible(true);  
                    m.invoke(menu, true);  
                } catch (Exception e) {  
                }  
            }  
        }  
        return super.onMenuOpened(featureId, menu);  
    }  



    private void setOverflowShowingAlways() {  
        try {  
            ViewConfiguration config = ViewConfiguration.get(this);  
            Field menuKeyField = ViewConfiguration.class  
                    .getDeclaredField("sHasPermanentMenuKey");  
            menuKeyField.setAccessible(true);  
            menuKeyField.setBoolean(config, false);  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }  

    @Override
    protected void onResume() {
    // TODO Auto-generated method stub
    super.onResume();
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.action_album:

            showDialog();

            Toast.makeText(this, "Action Refresh selected", Toast.LENGTH_SHORT).show();
            break;

        default:
            break;
    }
    return true;
    }



}

FragmentActivity的XML:

<?xml version="1.0" encoding="utf-8"?>
<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" >  

    <com.yixian.biodataintegration.PagerSlidingTabStrip  
        android:id="@+id/tabs"  
        android:layout_width="match_parent"  
        android:layout_height="40dp" />  

    <android.support.v4.view.ViewPager  
        android:id="@+id/pager"  
        android:layout_width="match_parent"  
        android:layout_height="wrap_content"  
        android:layout_below="@+id/tabs" />  


</RelativeLayout>  

谁能帮我解决问题?

3 个答案:

答案 0 :(得分:14)

尝试更改此代码块:

SupportMapFragment fm = (SupportMapFragment) getActivity()
                .getSupportFragmentManager().findFragmentById(R.id.google_map);
                // Getting GoogleMap object from the fragment
                mMap = fm.getMap();

为:

GoogleMap mMap = ((SupportMapFragment) this.getChildFragmentManager().findFragmentById(R.id.google_map)).getMap();

答案 1 :(得分:1)

试试这个......

  private GoogleMap googleMap;
  private SupportMapFragment mapFragment;
  ......

  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup viewGroup, Bundle bundle) {

        .......

        FragmentManager fManager= getChildFragmentManager();
        mapFragment = (SupportMapFragment) fManager
                .findFragmentById(R.id.ezeidHomeMap);
        mapFragment.getMapAsync(new OnMapReadyCallback()
        {
            public void onMapReady(GoogleMap map)
            {
                if (map == null)
                {
                    // showToast(getActivity(),
                            "Sorry! unable to create maps");
                } else
                {
                    googleMap = map;
                    googleMap.getUiSettings().setCompassEnabled(true);
                    googleMap.getUiSettings().setZoomControlsEnabled(true);
                    googleMap.getUiSettings().setMyLocationButtonEnabled(false);
                    googleMap.getUiSettings().setRotateGesturesEnabled(true);
                }
            }
        });

       .......
    }

答案 2 :(得分:0)

((SupportMapFragment) this.getChildFragmentManager().findFragmentById(R.id.google_map)).getMapAsync(this);

不要忘记实现以下回调:

@Override
public void onMapReady(GoogleMap googleMap) {
}