将mapView添加到片段时如何解决onStart错误

时间:2019-05-01 13:05:32

标签: java android google-maps android-fragments

我正在尝试将mapView放入片段中。但是onStart出现了问题,但是当我从onStart方法中删除mapView.onStart();时,地图在30秒后开始缓慢加载了吗?

  

尝试调用虚拟方法'void   com.google.android.gms.maps.MapView.onStart()”上的空对象   参考           在HomeActivity.onStart(HomeActivity.java:501)

(在这种情况下,第501行是“ mapView.onStart();”)

我尝试了不同的教程和重新格式化。我也尝试过使用其他Google API服务。我认为问题出在我使用的是碎片视图。

HomeActivity.java

public class HomeActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener, MyRecyclerViewAdapter.ItemClickListener, OnMapReadyCallback {


    private MapView mapView;
    private GoogleMap gmap;
    private static final String MAP_VIEW_BUNDLE_KEY = "MapViewBundleKey";


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

        session = new SessionHandler(getApplicationContext());
        final User user = session.getUserDetails();



        final View background = findViewById(R.id.home_background_view);
        final ViewPager viewPager = (ViewPager) findViewById(R.id.home_view_pager);
        MainPagerAdapter adapter = new MainPagerAdapter(getSupportFragmentManager());
        viewPager.setAdapter(adapter);

        TabLayout tabLayout = (TabLayout) findViewById(R.id.am_tab_layout);
        tabLayout.setupWithViewPager(viewPager);


        loadLocations();


        viewPager.setCurrentItem(1);





            @Override
            public void onPageSelected(int position) {
                if(position == 0)
                {
                    //code for first screen

                }if(position == 2){
                    //code for when screen is on the Map View

                    Bundle mapViewBundle = null;
                    if (savedInstanceState != null) {
                        mapViewBundle = savedInstanceState.getBundle(MAP_VIEW_BUNDLE_KEY);
                    }

                    mapView = findViewById(R.id.mapView);
                    mapView.onCreate(mapViewBundle);
                    mapView.getMapAsync(HomeActivity.this);
                }

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {

    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

    }

    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    @Override
    protected void onStart() {
        super.onStart();
        mapView.onStart();
    }

    @Override
    protected void onStop() {
        super.onStop();
        mapView.onStop();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        Bundle mapViewBundle = outState.getBundle(MAP_VIEW_BUNDLE_KEY);
        if (mapViewBundle == null) {
            mapViewBundle = new Bundle();
            outState.putBundle(MAP_VIEW_BUNDLE_KEY, mapViewBundle);
        }

        mapView.onSaveInstanceState(mapViewBundle);
    }


    @Override
    protected void onPause() {
        mapView.onPause();
        super.onPause();
    }
    @Override
    protected void onDestroy() {
        mapView.onDestroy();
        super.onDestroy();
    }
    @Override
    public void onLowMemory() {
        super.onLowMemory();
        mapView.onLowMemory();
    }
    @Override
    public void onMapReady(GoogleMap googleMap) {
        gmap = googleMap;
        //gmap.setMinZoomPreference(12);
        LatLng ny = new LatLng(40.7143528, -74.0059731);
        gmap.moveCamera(CameraUpdateFactory.newLatLng(ny));
    }


}

fragment_map.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    tools:background="@color/CafeSeaBlue"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    xmlns:tools="http://schemas.android.com/tools">

    <View
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="80dp"
        android:background="@drawable/card_background" />

    <android.support.v7.widget.AppCompatTextView
        android:id="@+id/latText1"
        android:layout_width="match_parent"
        android:layout_height="32dp"
        android:layout_below="@+id/longText"
        android:layout_marginTop="100dp"
        android:layout_marginBottom="50dp"
        android:background="@color/White"
        android:text="Map Screen"
        android:textAlignment="center"/>

    <com.google.android.gms.maps.MapView
        android:id="@+id/mapView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="150dp"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp" />
</FrameLayout>

Logcat

2019-05-01 14:15:33.397 20032-20032/im.craig.locateio E/AndroidRuntime: FATAL EXCEPTION: main
    Process: im.craig.locateio, PID: 20032
    java.lang.RuntimeException: Unable to start activity ComponentInfo{im.craig.locateio/im.craig.locateio.HomeActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.MapView.onStart()' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2778)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
        at android.app.ActivityThread.-wrap11(Unknown Source:0)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6494)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.MapView.onStart()' on a null object reference
        at im.craig.locateio.HomeActivity.onStart(HomeActivity.java:501)
        at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1334)
        at android.app.Activity.performStart(Activity.java:7029)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2741)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856) 
        at android.app.ActivityThread.-wrap11(Unknown Source:0) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589) 
        at android.os.Handler.dispatchMessage(Handler.java:106) 
        at android.os.Looper.loop(Looper.java:164) 
        at android.app.ActivityThread.main(ActivityThread.java:6494) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)

2 个答案:

答案 0 :(得分:0)

尝试使用Oncreate方法而不是onPageSelected方法初始化MapView。将其从onPageSelected方法中删除,并在OnCreate方法中进行。

mapView = findViewById(R.id.mapView);

此行下面会更好

viewPager.setCurrentItem(1);

所以看起来像这样。

viewPager.setCurrentItem(1);
mapView = findViewById(R.id.mapView);

答案 1 :(得分:-1)

您需要在Fragment#OnDestroyView而不是Fragment#onDestroy中调用onDestroy。掌握正确的生命周期将解决您的问题。