地图初始化时出现NullPointerException

时间:2013-11-29 11:42:47

标签: android android-fragments supportmapfragment

我在使用SupportMapFragment进行地图初始化时获得了nullpointer异常。我也添加了google play lib。它在onStart()方法的第map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();行抛出异常。

我的代码是:

public class MapSectionFragment extends Fragment {

GoogleMap map;
@Override
        public void onStart() {
            // TODO Auto-generated method stub
            super.onStart();

            map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();

        }

        public Fragment newInstance() {
            return new MapSectionFragment();
        }

View rootView = null;

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

            try{

                if (null == savedInstanceState)
                    rootView = inflater.inflate(R.layout.lay_search_map, container,
                            false);

                map = ((SupportMapFragment) getSupportFragmentManager()
                        .findFragmentById(R.id.map)).getMap();          
}

}

lay_search_map.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"
    android:background="@android:color/transparent"
    tools:context=".LocatorMainActivity$DummySectionFragment" >


    <fragment
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="fill_parent"
        android:layout_height="match_parent" />

</RelativeLayout>

这是我的错误日志:

11-30 14:37:13.100: E/AndroidRuntime(6159): FATAL EXCEPTION: main
11-30 14:37:13.100: E/AndroidRuntime(6159): java.lang.NullPointerException
11-30 14:37:13.100: E/AndroidRuntime(6159):     at com.agile.pbc.LocatorMainActivity$MapSectionFragment.onStart(LocatorMainActivity.java:533)
11-30 14:37:13.100: E/AndroidRuntime(6159):     at android.support.v4.app.Fragment.performStart(Fragment.java:1524)
11-30 14:37:13.100: E/AndroidRuntime(6159):     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:957)
11-30 14:37:13.100: E/AndroidRuntime(6159):     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)
11-30 14:37:13.100: E/AndroidRuntime(6159):     at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
11-30 14:37:13.100: E/AndroidRuntime(6159):     at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1467)
11-30 14:37:13.100: E/AndroidRuntime(6159):     at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:472)
11-30 14:37:13.100: E/AndroidRuntime(6159):     at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
11-30 14:37:13.100: E/AndroidRuntime(6159):     at android.support.v4.view.ViewPager.populate(ViewPager.java:1068)
11-30 14:37:13.100: E/AndroidRuntime(6159):     at android.support.v4.view.ViewPager.populate(ViewPager.java:914)
11-30 14:37:13.100: E/AndroidRuntime(6159):     at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1436)
11-30 14:37:13.100: E/AndroidRuntime(6159):     at android.view.View.measure(View.java:12922)
11-30 14:37:13.100: E/AndroidRuntime(6159):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4706)
11-30 14:37:13.100: E/AndroidRuntime(6159):     at android.widget.FrameLayout.onMeasure(FrameLayout.java:293)
11-30 14:37:13.100: E/AndroidRuntime(6159):     at android.view.View.measure(View.java:12922)
11-30 14:37:13.100: E/AndroidRuntime(6159):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4706)
11-30 14:37:13.100: E/AndroidRuntime(6159):     at android.widget.FrameLayout.onMeasure(FrameLayout.java:293)
11-30 14:37:13.100: E/AndroidRuntime(6159):     at android.view.View.measure(View.java:12922)
11-30 14:37:13.100: E/AndroidRuntime(6159):     at android.widget.LinearLayout.measureVertical(LinearLayout.java:822)
11-30 14:37:13.100: E/AndroidRuntime(6159):     at android.widget.LinearLayout.onMeasure(LinearLayout.java:563)
11-30 14:37:13.100: E/AndroidRuntime(6159):     at android.view.View.measure(View.java:12922)
11-30 14:37:13.100: E/AndroidRuntime(6159):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4706)
11-30 14:37:13.100: E/AndroidRuntime(6159):     at android.widget.FrameLayout.onMeasure(FrameLayout.java:293)
11-30 14:37:13.100: E/AndroidRuntime(6159):     at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2261)
11-30 14:37:13.100: E/AndroidRuntime(6159):     at android.view.View.measure(View.java:12922)
11-30 14:37:13.100: E/AndroidRuntime(6159):     at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1255)
11-30 14:37:13.100: E/AndroidRuntime(6159):     at android.view.ViewRootImpl.handleMessage(ViewRootImpl.java:2649)
11-30 14:37:13.100: E/AndroidRuntime(6159):     at android.os.Handler.dispatchMessage(Handler.java:99)
11-30 14:37:13.100: E/AndroidRuntime(6159):     at android.os.Looper.loop(Looper.java:137)
11-30 14:37:13.100: E/AndroidRuntime(6159):     at android.app.ActivityThread.main(ActivityThread.java:4507)
11-30 14:37:13.100: E/AndroidRuntime(6159):     at java.lang.reflect.Method.invokeNative(Native Method)
11-30 14:37:13.100: E/AndroidRuntime(6159):     at java.lang.reflect.Method.invoke(Method.java:511)
11-30 14:37:13.100: E/AndroidRuntime(6159):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:978)
11-30 14:37:13.100: E/AndroidRuntime(6159):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:745)
11-30 14:37:13.100: E/AndroidRuntime(6159):     at dalvik.system.NativeStart.main(Native Method)

2 个答案:

答案 0 :(得分:0)

尝试使用MapFragment -

    map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
            .getMap();
 try {
            MapsInitializer.initialize(this);
        } catch (GooglePlayServicesNotAvailableException e) {
            e.printStackTrace();
        }

答案 1 :(得分:0)

我无法理解在片段内显示地图的方式,所以我就这样上去了,

public class MapFragment extends Activity {
// Google Map
private GoogleMap googleMap;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.mapsview);

    try {
        // Loading map
        initilizeMap();

    } catch (Exception e) {
        e.printStackTrace();
    }
}

// function to load map. If map is not created it will create it for you
private void initilizeMap() {
    if (googleMap == null) {
        googleMap = ((com.google.android.gms.maps.MapFragment) getFragmentManager()
                .findFragmentById(R.id.map)).getMap();

        // check if map is created successfully or not
        if (googleMap == null) {
            Toast.makeText(getApplicationContext(),
                    "Sorry! Unable to load map", Toast.LENGTH_SHORT).show();
        }
    }
    // create marker and setting latitude and longitude
    MarkerOptions marker = new MarkerOptions()
            .position(
                    new LatLng(Double.parseDouble(DetailActivity.Lat),
                            Double.parseDouble(DetailActivity.Long)))
            .title(DetailActivity.name + "    "
                    + PriceFragment.actualprice.getText().toString()
                    + " -- " + PriceFragment.dealPrice.getText().toString());

    // adding marker
    googleMap.addMarker(marker);
}

public void onResume() {
    initilizeMap();
    super.onResume();
    // getLatLongValues();
}

上述类是地图的活动。

现在我只获得片段内活动的窗口。

public class MapExtend extends Fragment {
private static final String KEY_STATE_BUNDLE = "localActivityManagerState";

private LocalActivityManager mLocalActivityManager;

protected LocalActivityManager getLocalActivityManager() {
    return mLocalActivityManager;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Bundle state = null;
    if (savedInstanceState != null) {
        state = savedInstanceState.getBundle(KEY_STATE_BUNDLE);
    }

    mLocalActivityManager = new LocalActivityManager(getActivity(), true);
    mLocalActivityManager.dispatchCreate(state);
}

public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // This is where you specify you activity class
    Intent i = new Intent(getActivity(), MapFragment.class);
    i.putExtra("lat", DetailActivity.Lat);
    i.putExtra("long", DetailActivity.Long);
    i.putExtra("name", DetailActivity.name);
    Window w = mLocalActivityManager.startActivity("tag", i);
    View currentView = w.getDecorView();
    currentView.setVisibility(View.VISIBLE);
    currentView.setFocusableInTouchMode(true);
    ((ViewGroup) currentView)
            .setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
    // View newView = inflater.inflate(currentView, container, false);
    // currentView.setId(R.layout.maplayout);
    // View newView = inflater.inflate(currentView.getId(),
    // container,false);
    return currentView;
}

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putBundle(KEY_STATE_BUNDLE,
            mLocalActivityManager.saveInstanceState());
}

@Override
public void onResume() {
    super.onResume();
    mLocalActivityManager.dispatchResume();
}

@Override
public void onPause() {
    super.onPause();
    mLocalActivityManager.dispatchPause(getActivity().isFinishing());
}

@Override
public void onStop() {
    super.onStop();
    mLocalActivityManager.dispatchStop();
}

@Override
public void onDestroy() {
    super.onDestroy();
    mLocalActivityManager.dispatchDestroy(getActivity().isFinishing());
}

我用这样的方式得到了我的地图。