GoogleMapSnapshot NullPointerException - PullRequest
0 голосов
/ 04 июня 2018

Я пытаюсь сделать снимок экрана с Google Maps android и передать изображение в новый вид деятельности, но постоянно получаю эту ошибку:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.GoogleMap.snapshot(com.google.android.gms.maps.GoogleMap$SnapshotReadyCallback)' on a null object reference
    at com.jjoey.transportr.activities.BookRideActivity.initViews(BookRideActivity.java:480)
    at com.jjoey.transportr.activities.BookRideActivity.onCreate(BookRideActivity.java:101)
    at android.app.Activity.performCreate(Activity.java:5990)

Я пытался написать код в onResume and onMapReady методахактивность, но ошибка сохраняется.

Вот мой код активности:

public class BookRideActivity extends FirebaseUtils implements OnMapReadyCallback {

private static final String TAG = BookRideActivity.class.getSimpleName();

private static final int LOC_REQ_CODE = 2035;

private Toolbar toolbar;
private ImageView backIV;
private SharedPrefsHelper prefsHelper;

private SupportMapFragment mapFragment;
private GoogleMap mGmap;
private LocationRequest locationRequest;
private FusedLocationProviderClient fusedLocationProviderClient;
private LocationCallback callback;
private Location mCurrLocation;
private Marker marker;

private Bitmap locnImg;

private EditText startET, dropET, et_coupon, et_payment_options, et_rider;
private TextView estimatedPUTimeTV;
private Button bookNowBtn, cancelBtn;

private double lat = 0f, lon = 0f;
private String start = null, drop = null;
private boolean isValid = false;

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

    initViews();
    start = getIntent().getStringExtra("start_addr");
    drop = getIntent().getStringExtra("dest_addr");

    if (start != null && drop != null) {
        startET.setText(start);
        dropET.setText(drop);
    } else {
        clearInputs();
    }

    setSupportActionBar(toolbar);
    prefsHelper = new SharedPrefsHelper(this);
    prefsHelper.setLoggedOut(false);

    backIV.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            startActivity(new Intent(BookRideActivity.this, ClientHomeActivity.class));
        }
    });

    et_coupon.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Log.d(TAG, "Coupon Clicked");
            showCouponDialog();
        }
    });

    checkPerms();
    handlePlacesInput();

}

private void checkPerms() {
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        reqPerms();
    } else {
        startLocationListener();
    }
}

private void reqPerms() {
    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, LOC_REQ_CODE);
}

private void startLocationListener() {

    fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);

    locationRequest = LocationRequest.create();
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    locationRequest.setSmallestDisplacement(DISPLACEMENT);
    locationRequest.setFastestInterval(FASTEST_INTERVAL);
    locationRequest.setInterval(UPDATE_INTERVAL);

    LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
    builder.addLocationRequest(locationRequest);

    LocationSettingsRequest settingsRequest = builder.build();
    SettingsClient client = LocationServices.getSettingsClient(this);
    client.checkLocationSettings(settingsRequest);

    drawLocationOnMap();

}

private void drawLocationOnMap() {
    callback = new LocationCallback() {
        @Override
        public void onLocationResult(LocationResult locationResult) {
            super.onLocationResult(locationResult);

            mCurrLocation = locationResult.getLastLocation();
            if (marker != null && mCurrLocation != null) {
                marker.remove();

                lat = mCurrLocation.getLatitude();
                lon = mCurrLocation.getLongitude();

            }
            MarkerOptions options = new MarkerOptions();
            options.position(new LatLng(lat, lon));
            options.title("You");
            options.icon(BitmapDescriptorFactory.fromResource(R.drawable.user_marker));

            marker = mGmap.addMarker(options);
            mGmap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lon), 18.0f));

        }
    };

    if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
        fusedLocationProviderClient.requestLocationUpdates(locationRequest, callback, Looper.myLooper());
        //mGmap.setMyLocationEnabled(true);
    } else {
        reqPerms();
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    switch (requestCode) {
        case LOC_REQ_CODE:
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                startLocationListener();
            }
            break;
    }
}

private void handlePlacesInput() {
    startET.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            startET.setText("");
            try {
                Intent intent =
                        new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_OVERLAY)
                                .build(BookRideActivity.this);
                startActivityForResult(intent, START_PLACE_AUTOCOMPLETE_REQUEST_CODE);
            } catch (GooglePlayServicesRepairableException e) {
                Log.d(TAG, "Play-Services-Repairable Err:\t" + e.getMessage());
            } catch (GooglePlayServicesNotAvailableException e) {
                Log.d(TAG, "Play-Services-Unavailable Err:\t" + e.getMessage());
            }
        }
    });

    dropET.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            dropET.setText("");
            try {
                Intent intent =
                        new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_OVERLAY)
                                .build(BookRideActivity.this);
                startActivityForResult(intent, DROP_PLACE_AUTOCOMPLETE_REQUEST_CODE);
            } catch (GooglePlayServicesRepairableException e) {
                Log.d(TAG, "Play-Services-Repairable Err:\t" + e.getMessage());
            } catch (GooglePlayServicesNotAvailableException e) {
                Log.d(TAG, "Play-Services-Unavailable Err:\t" + e.getMessage());
            }
        }
    });

}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode) {
        case START_PLACE_AUTOCOMPLETE_REQUEST_CODE:
            if (resultCode == RESULT_OK) {
                Place place = PlaceAutocomplete.getPlace(this, data);
                String txt = place.getAddress().toString();
                startET.setText(txt);
            } else if (resultCode == PlaceAutocomplete.RESULT_ERROR) {
                Status status = PlaceAutocomplete.getStatus(this, data);
                Log.d(TAG, status.getStatusMessage());

            } else if (resultCode == RESULT_CANCELED) {
            }
            break;
        case DROP_PLACE_AUTOCOMPLETE_REQUEST_CODE:
            if (resultCode == RESULT_OK) {
                Place place = PlaceAutocomplete.getPlace(this, data);
                String txt = place.getAddress().toString();
                dropET.setText(txt);
            } else if (resultCode == PlaceAutocomplete.RESULT_ERROR) {
                Status status = PlaceAutocomplete.getStatus(this, data);
                Log.d(TAG, status.getStatusMessage());

            } else if (resultCode == RESULT_CANCELED) {
            }
            break;
    }
}

private boolean validate() {
    String startAddr = startET.getText().toString();
    String destAddr = dropET.getText().toString();

    if (TextUtils.isEmpty(startAddr) && TextUtils.isEmpty(destAddr)) {
        isValid = false;
    } else if (!TextUtils.isEmpty(startAddr) && !TextUtils.isEmpty(destAddr)) {
        isValid = true;
    }
    return true;
}

private void clearInputs() {
    startET.setText("");
    dropET.setText("");
}

private void initViews() {
    toolbar = findViewById(R.id.toolbar);
    backIV = findViewById(R.id.backIV);
    dropET = findViewById(R.id.dropLocationET);
    startET = findViewById(R.id.startLocationET);
    bookNowBtn = findViewById(R.id.bookNowBtn);
    cancelBtn = findViewById(R.id.cancelBtn);

    GoogleMap.SnapshotReadyCallback snapshotReadyCallback = new GoogleMap.SnapshotReadyCallback() {
        @Override
        public void onSnapshotReady(Bitmap bitmap) {
            locnImg = bitmap;
            Log.d(TAG, "Snapshot Ready");
        }
    };

    mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.mapFragment);
    mapFragment.getMapAsync(this);

    mGmap.snapshot(snapshotReadyCallback);
    Log.d(TAG, "Snapshot Taken");

}

@Override
public void onMapReady(GoogleMap googleMap) {
    mGmap = googleMap;

    View mapBtn = (View) ((View) mapFragment.getView().findViewById(Integer.parseInt("1")).getParent()).findViewById(Integer.parseInt("2"));
    RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) mapBtn.getLayoutParams();
    params.addRule(RelativeLayout.ALIGN_PARENT_TOP, 0);
    params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
    params.setMargins(0, 0, 30, 30);

}

}

Я пытался выполнить этот урок , но это не такв моем случае не работает. Ошибка возникает при попытке mGmap.snapshot(snapshotReadyCallback);.Я инициализировал карту в строках выше и получил местоположение, используя FusedLocationProviderClient api.

Может кто-нибудь помочь мне понять, почему она выдает эту ошибку?Спасибо

...