简体   繁体   中英

NavigationView on a null object reference in Mapbox Android

I want to navigate between route. I have been successfully created a route between two points but i am having error while i am trying to start navigation between them. That something like NavigationView.onCreate(android.os.Bundle) on a null object reference. How can i achieve this and where i am doing a mistake?

public class NavigationActivity extends AppCompatActivity implements OnMapReadyCallback{

    public static final String TAG = "NavigationActivity";
    private MapView mapView;
    private TDD tdd;
    private Point originPosition, dstPosition;
    private Double originLat, originLng, dstLat, dstLng;
    private LatLng originLatLng, dstLatLng;
    private MapboxMap map;
    private NavigationMapRoute navigationMapRoute;
    private DirectionsRoute currentRoute;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Mapbox.getInstance(this, getString(R.string.access_token));
        setContentView(R.layout.activity_navigation);
        MapBox(savedInstanceState);
//        originLatLng = new LatLng(24.8955, 67.0271);
//        dstLatLng = new LatLng(24.9180, 67.0971);

    }

    @Override
    public void onMapReady(@NonNull MapboxMap mapboxMap) {
        this.map = mapboxMap;

        mapboxMap.setStyle(Style.MAPBOX_STREETS, new Style.OnStyleLoaded() {
            @Override
            public void onStyleLoaded(@NonNull Style style) {

                originPosition = Point.fromLngLat(originLatLng.getLongitude(), originLatLng.getLatitude());
                dstPosition = Point.fromLngLat(dstLatLng.getLongitude(), dstLatLng.getLatitude());

                MarkerOptions options = new MarkerOptions();
                options.title("Source");
                options.position(originLatLng);

                MarkerOptions options1 = new MarkerOptions();
                options1.title("Destination");
                options1.position(dstLatLng);

                mapboxMap.addMarker(options);
                mapboxMap.addMarker(options1);
                getRoute(originPosition, dstPosition);

                LatLngBounds latLngBounds = new LatLngBounds.Builder()
                        .include(originLatLng) // Northeast
                        .include(dstLatLng) // Southwest
                        .build();

                mapboxMap.easeCamera(CameraUpdateFactory.newLatLngBounds(latLngBounds, 50), 5000);


            }
        });


    }

    private void MapBox(Bundle savedInstanceState)
    {
        mapView = findViewById(R.id.mapView);
        mapView.onCreate(savedInstanceState);
        mapView.getMapAsync(this);

        Intent i = getIntent();
        tdd = (TDD) i.getSerializableExtra("tdd");

        originLat = Double.parseDouble(tdd.getmSrcLat());
        originLng = Double.parseDouble(tdd.getmSrcLng());
        dstLat = Double.parseDouble(tdd.getmDstLat());
        dstLng = Double.parseDouble(tdd.getmDstLng());

        originLatLng = new LatLng(originLat, originLng);
        dstLatLng = new LatLng(dstLat, dstLng);
    }

    private void getRoute(Point origin, Point destination)
    {
        NavigationRoute.builder(NavigationActivity.this)
                .accessToken(Mapbox.getAccessToken())
                .origin(origin)
                .destination(destination)
                .build()
                .getRoute(new Callback<DirectionsResponse>() {
                    @Override
                    public void onResponse(Call<DirectionsResponse> call, Response<DirectionsResponse> response) {
                        if (response.body() == null)
                        {
                            Usable.logMessage(TAG, "No routes found, Check User and Access Token..");
                            return;
                        } else if (response.body().routes().size() == 0)
                        {
                            Usable.logMessage(TAG, "No routes found..");
                            return;
                        }


                        Log.e(TAG, "Direction Route: "+ response.body().routes().size());

                        currentRoute = response.body().routes().get(0);
                        navigationMapRoute = new NavigationMapRoute(null, mapView, map);
                        navigationMapRoute.addRoute(currentRoute);

                        navigationRoute(currentRoute);

                    }

                    @Override
                    public void onFailure(Call<DirectionsResponse> call, Throwable t) {
                        Log.e(TAG, "Error: "+ t.getMessage());

                    }
                });

    }

    private void navigationRoute(DirectionsRoute cr)
    {
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            public void run() {
                NavigationLauncherOptions options = NavigationLauncherOptions.builder()
                        .directionsRoute(cr)
                        .shouldSimulateRoute(true)
                        .build();
                NavigationLauncher.startNavigation(NavigationActivity.this, options);
            }
        }, 5000);
    }


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

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

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

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

    @Override
    protected void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        mapView.onLowMemory();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
    }
}
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:mapbox="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:weightSum="100"
    tools:context=".NavigationActivity">


    <com.mapbox.mapboxsdk.maps.MapView
        android:id="@+id/mapView"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="90"
        mapbox:mapbox_cameraTargetLat="24.8607"
        mapbox:mapbox_cameraTargetLng="67.0011"
        mapbox:mapbox_cameraZoom="11"
        />

    <Button
        android:id="@+id/startNavigation"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="10"
        android:text="Start Navigation"
        android:textColor="@color/white"
        android:layout_margin="2dp"
        android:enabled="false"
        android:background="@drawable/ripple_effect_button"/>

</LinearLayout>
2020-05-13 13:05:58.199 20171-20171/com.devaj.googlemaps E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.devaj.googlemaps, PID: 20171
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.devaj.googlemaps/com.mapbox.services.android.navigation.ui.v5.MapboxNavigationActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.mapbox.services.android.navigation.ui.v5.NavigationView.onCreate(android.os.Bundle)' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2988)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3073)
        at android.app.ActivityThread.-wrap11(Unknown Source:0)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1734)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:7025)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:441)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.mapbox.services.android.navigation.ui.v5.NavigationView.onCreate(android.os.Bundle)' on a null object reference
        at com.mapbox.services.android.navigation.ui.v5.MapboxNavigationActivity.onCreate(MapboxNavigationActivity.java:32)
        at android.app.Activity.performCreate(Activity.java:7258)
        at android.app.Activity.performCreate(Activity.java:7249)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1222)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2941)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3073) 
        at android.app.ActivityThread.-wrap11(Unknown Source:0) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1734) 
        at android.os.Handler.dispatchMessage(Handler.java:106) 
        at android.os.Looper.loop(Looper.java:164) 
        at android.app.ActivityThread.main(ActivityThread.java:7025) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:441) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408) 

It works for me. I assume that you are missing a dependency.

Please make sure to include this into your build.gradle files:

Project Level build.gradle:

 allprojects { repositories { google() jcenter() maven { url 'https://mapbox.bintray.com/mapbox' } } }

Application level build.gradle:

 dependencies { implementation 'com.mapbox.mapboxsdk:mapbox-android-navigation-ui:0.42.6' }

Please let me know if that helped!

Your NavigationActivity and MapboxNavigationActivity (predefined class of Navigation SDK) both has the same xml layout name ie activity_navigation. This is the reason of null pointer exception and crash. When you were trying to start navigation, app was calling activity_navigation of NavigationActivity instead of MapboxNavigationActivity .

So by refactoring your activity name changing your xml name from activity_navigation to activity_main can solve the issue.

请检查此图片链接

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM