You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何用onSuccess获取的位置替换ROUTE_ORIGIN?空指针问题求助

Fixing the NullPointerException for Dynamic Location-Based Route Origin

Hey there, let's tackle this NullPointerException you're hitting. The root cause boils down to timing and incorrect variable initialization:

Why the Crash Happens

  • You declared ROUTE_ORIGIN as a final class-level variable and tried to initialize it with location.longitude()/location.latitude(). But when your ArActivity first loads, location is still null—the location callback hasn't fired yet to populate it. That's why calling methods on a null object throws the NPE.
  • The final modifier also locks ROUTE_ORIGIN into its initial (invalid) value, so you can't update it later once you get the real user location.

Step-by-Step Solution

1. Update the Route Origin Variable

First, remove the final modifier and stop initializing it immediately—we'll set it dynamically once we have a valid location:

// Remove final and initialize to null (we'll populate this later)
private Point routeOrigin;
// Keep the destination as a fixed final value
private final Point ROUTE_DESTINATION = Point.fromLngLat(101.769116, 2.923220);

2. Modify the Location Callback to Trigger Route Setup

Update your onSuccess method to set the origin and start the route initialization only after we have a valid location:

locationCallback = new LocationEngineCallback<LocationEngineResult>() {
    @Override
    public void onSuccess(LocationEngineResult result) {
        if (result.getLastLocation() == null) {
            Toast.makeText(ArActivity.this, "Failed to retrieve your location", Toast.LENGTH_SHORT).show();
            return;
        }
        // Populate the origin with real user coordinates
        routeOrigin = Point.fromLngLat(
            result.getLastLocation().getLongitude(),
            result.getLastLocation().getLatitude()
        );
        
        // Optional: Update your TextView to display the location
        tvlocation.setText(String.format("Lat: %.6f, Lng: %.6f", 
            routeOrigin.latitude(), routeOrigin.longitude()));
        
        // Only start the route if we have a valid origin and navigation is initialized
        if (routeOrigin != null && navigationWasStarted) {
            initDirectionsRoute();
        }
    }

    @Override
    public void onFailure(@NonNull Exception exception) {
        Toast.makeText(ArActivity.this, "Location error: " + exception.getMessage(), Toast.LENGTH_SHORT).show();
        VisionLogger.Companion.e(TAG, exception.toString());
    }
};

3. Secure the Route Initialization Method

Add a null check to initDirectionsRoute to avoid invalid route requests, and use the dynamic routeOrigin instead of the old constant:

private void initDirectionsRoute() {
    if (routeOrigin == null) {
        Toast.makeText(this, "Waiting for your location...", Toast.LENGTH_SHORT).show();
        return;
    }
    // Request route with the dynamic origin and fixed destination
    NavigationRoute.builder(this)
        .accessToken(getString(R.string.mapbox_access_token))
        .origin(routeOrigin)
        .destination(ROUTE_DESTINATION)
        .build()
        .getRoute(new Callback<DirectionsResponse>() {
            @Override
            public void onResponse(Call<DirectionsResponse> call, Response<DirectionsResponse> response) {
                if (response.body() == null || response.body().routes().isEmpty()) {
                    Toast.makeText(ArActivity.this, "No valid route found", Toast.LENGTH_SHORT).show();
                    return;
                }
                DirectionsRoute route = response.body().routes().get(0);
                mapboxNavigation.startNavigation(route);
                // Update AR route visualization
                VisionArManager.setRoute(new Route(
                    getRoutePoints(route), route.duration().floatValue(), "", ""
                ));
            }

            @Override
            public void onFailure(Call<DirectionsResponse> call, Throwable t) {
                Toast.makeText(ArActivity.this, "Route request failed: " + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
}

4. Remove Early Route Initialization

In your startNavigation method, delete the line initDirectionsRoute();—we now trigger this only after we have a valid location, so calling it early would still use a null origin.


Why This Works

  • We no longer try to initialize the route origin with a null location during class setup
  • We wait until we have real user coordinates before requesting a route
  • Added null checks and user feedback for edge cases (like location fetch failures or missing routes)

内容的提问来源于stack exchange,提问作者estherooi

火山引擎 最新活动