-2

I'm trying to place a mapView into a fragment. It is having issues with the onStart, however, when I remove the mapView.onStart(); from the onStart method, after 30 seconds the map begins to slowly load?

Attempt to invoke virtual method 'void com.google.android.gms.maps.MapView.onStart()' on a null object reference at HomeActivity.onStart(HomeActivity.java:501)

(Line 501 in this case is "mapView.onStart();")

I've tried different tutorials and reformatting. I have also tried using different google api services. I think the issue lies in that I am using a fragmented view.

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)
RalphLDN
  • 1
  • 2

2 Answers2

0

Try to initialize the MapView in Oncreate method, not in onPageSelected method. remove it from onPageSelected method and do it in the OnCreate method.

mapView = findViewById(R.id.mapView);

Below this line would be better

viewPager.setCurrentItem(1);

So it will look like this.

viewPager.setCurrentItem(1);
mapView = findViewById(R.id.mapView);
Yasiru Nayanajith
  • 1,647
  • 17
  • 20
  • Thanks, I have tried moving this into the onCreate however that doesnt seem to work. I then tried moving everything within that section into the onCreate and i got this error Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.MapView.onCreate(android.os.Bundle)' on a null object reference at im.craig.locateio.HomeActivity.onCreate(HomeActivity.java:166) Line 166 is "mapView.onCreate(mapViewBundle);" – RalphLDN May 01 '19 at 13:32
-1

you need to call onDestroy as part of Fragment#OnDestroyView instead of Fragment#onDestroy. Hooking into the correct lifecycle will resolve your issue.