启用onRequestpermission后,在我的位置显示标记时出现问题。我的所有代码似乎都没问题,但我无法理解每次我尝试启用我的准时位置切换它崩溃
java.lang.NullPointerException:尝试调用虚方法 ' float com.google.android.gms.maps.model.Marker.getRotation()'在...上 null对象引用 在 com.hushtagstudios.mac.towmedelivery.DrawerActivity.rotateMarker(DrawerActivity.java:387) 在 com.hushtagstudios.mac.towmedelivery.DrawerActivity.access $ 300(DrawerActivity.java:52) 在 com.hushtagstudios.mac.towmedelivery.DrawerActivity $ 9.onComplete(DrawerActivity.java:368)
package com.hushtagstudios.mac.towmedelivery;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
import com.firebase.geofire.GeoFire;
import com.firebase.geofire.GeoLocation;
import com.github.glomadrian.materialanimatedswitch.MaterialAnimatedSwitch;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class DrawerActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListener{
public static GoogleMap mMap;
//play services res
private static final int MY_PERMISSION_REQUEST_CODE = 7000;
private static final int PLAY_SERVICES_RES_REQUEST = 7001;
private LocationRequest mLocationRequest;
private GoogleApiClient mGoogleApiClient;
private Location mLastLocation;
private static int UPDATE_INTERVAL = 5000;
private static int FASTEST_INTERVAL =3000;
private static int DISPLACEMENT = 10;
DatabaseReference drivers;
GeoFire geoFire;
Marker mCurrent;
MaterialAnimatedSwitch location_switch;
SupportMapFragment mapFragment;
TableRow myAccount, history, payments, notifications, invite, help, about, driveWithTowMe;
TextView name, email;
ImageView profilePicture;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_drawer);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
location_switch = (MaterialAnimatedSwitch)findViewById(R.id.location_switch);
location_switch.setOnCheckedChangeListener(new MaterialAnimatedSwitch.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(boolean IsOnline) {
if (IsOnline){
startLocationUpdates();
displayLocation();
Snackbar.make(mapFragment.getView(),"You are online", Snackbar.LENGTH_SHORT)
.show();
}else {
stopLocationUpdates();
mCurrent.remove();
Snackbar.make(mapFragment.getView(),"You are offline", Snackbar.LENGTH_SHORT)
.show();
}
}
});
//geo fire
drivers = FirebaseDatabase.getInstance().getReference("DeliveryDatabase");
geoFire = new GeoFire(drivers);
setUpLocation();
final DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
name = (TextView) findViewById(R.id.name);
email = (TextView) findViewById(R.id.email);
profilePicture = (ImageView) findViewById(R.id.profilePicture);
myAccount = (TableRow) findViewById(R.id.myAccount);
history = (TableRow) findViewById(R.id.history);
payments = (TableRow) findViewById(R.id.myPayments);
notifications = (TableRow) findViewById(R.id.notifications);
help = (TableRow) findViewById(R.id.help);
about = (TableRow) findViewById(R.id.about);
driveWithTowMe = (TableRow) findViewById(R.id.DriveWithTowMe);
myAccount.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent openMyAccount = new Intent(DrawerActivity.this, Dashboard.class);
startActivity(openMyAccount);
drawer.closeDrawer(GravityCompat.START);
finish();
}
});
history.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent openNotifications = new Intent(DrawerActivity.this, TripBill.class);
startActivity(openNotifications);
drawer.closeDrawer(GravityCompat.START);
}
});
payments.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent openNotifications = new Intent(DrawerActivity.this, EarningsFragment.class);
startActivity(openNotifications);
drawer.closeDrawer(GravityCompat.START);
}
});
notifications.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent openNotifications = new Intent(DrawerActivity.this, NotificationsFragment.class);
startActivity(openNotifications);
drawer.closeDrawer(GravityCompat.START);
}
});
help.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent openHelp = new Intent(DrawerActivity.this, HelpActivity.class);
startActivity(openHelp);
drawer.closeDrawer(GravityCompat.START);
}
});
driveWithTowMe.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
drawer.closeDrawer(GravityCompat.START);
}
});
about.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent openAbout = new Intent(DrawerActivity.this, About.class);
startActivity(openAbout);
drawer.closeDrawer(GravityCompat.START);
}
});
}
//Press Ctrl+O
//Because we request runtime permission, we need override OnRequestPermissionResult method
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode){
case MY_PERMISSION_REQUEST_CODE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
if (checkPlayServices()){
buildGoogleApiClient();
createLocationRequest();
if (location_switch.isChecked()){
displayLocation();
}
}
}
}
}
private void setUpLocation() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)!= PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED )
{
//Request runtime permissions
ActivityCompat.requestPermissions(this, new String[]{
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION
},MY_PERMISSION_REQUEST_CODE);
} else {
if (checkPlayServices()){
buildGoogleApiClient();
createLocationRequest();
if (location_switch.isChecked()){
displayLocation();
}
}
}
}
private void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(UPDATE_INTERVAL);
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setSmallestDisplacement(DISPLACEMENT);
}
private void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
private boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS){
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode))
GooglePlayServicesUtil.getErrorDialog(resultCode,this,PLAY_SERVICES_RES_REQUEST).show();
else {
Toast.makeText(this, "This device is not supported", Toast.LENGTH_SHORT).show();
finish();
}
return false;
}
return true;
}
private void stopLocationUpdates() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)!= PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED ){
return;
}
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
private void displayLocation() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)!= PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED ){
return;
}
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLastLocation != null){
if (location_switch.isChecked()){
final double latitude = mLastLocation.getLatitude();
final double longitude = mLastLocation.getLongitude();
//update to firebase
geoFire.setLocation(FirebaseAuth.getInstance().getCurrentUser().getUid(), new GeoLocation(latitude, longitude), new GeoFire.CompletionListener() {
@Override
public void onComplete(String key, DatabaseError error) {
//Add Marker
if (mCurrent != null){
mCurrent.remove();
mCurrent = mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_towtruck))
.position(new LatLng(latitude,longitude))
.title("You"));
}
//move camera to this position
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude,longitude),15.0f));
//Draw animation rotate marker
rotateMarker(mCurrent,-360, mMap);
}
});
}
}
else {
Log.d("ERROR", "Cannot get your location");
}
}
private void rotateMarker(final Marker mCurrent, final float i, GoogleMap mMap) {
final Handler handler = new Handler();
final long start = SystemClock.uptimeMillis();
final float startRotation = mCurrent.getRotation();
final long duration = 1500;
final LinearInterpolator interpolator = new LinearInterpolator();
handler.post(new Runnable() {
@Override
public void run() {
long elapsed = SystemClock.uptimeMillis() - start;
float t = interpolator.getInterpolation((float)elapsed/duration);
float rot = t * i + (1 - t ) * startRotation;
mCurrent.setRotation(-rot > 180?rot/2:rot);
if (t<1.0){
handler.postDelayed(this,16);
}
}
});
}
private void startLocationUpdates() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)!= PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED ){
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.drawer, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
}
@Override
public void onLocationChanged(Location location) {
mLastLocation = location;
displayLocation();
}
@Override
public void onConnected(@Nullable Bundle bundle) {
displayLocation();
startLocationUpdates();
}
@Override
public void onConnectionSuspended(int i) {
mGoogleApiClient.connect();
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}
}
答案 0 :(得分:0)
我没有得到您的代码,但我想我知道问题所在,因为您从未分配过mCurrent
变量,它始终为空。
在您的方法displayLocation()
此块
if (mCurrent != null){
mCurrent.remove();
mCurrent = mMap.addMarker(new MarkerOptions().icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_towtruck))
.position(new LatLng(latitude, longitude))
.title("You"));
}
应更改为此选项以启用mCurrent
if (mCurrent != null){
mCurrent.remove();
}
mCurrent = mMap.addMarker(new MarkerOptions().icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_towtruck))
.position(new LatLng(latitude, longitude))
.title("You"));