Я действительно застрял с этой ошибкой, буквально перепробовал все, что мог придумать, чтобы избежать NPE в методе getLatitude ...
Может кто-нибудь проверить мой код и порекомендовать решение?
Это работает, только если я жестко кодирую в некоторых координатах для Lat & Lng, но это не то, что я хочу сделать. Заранее спасибо.
CODE
public class CoPilotMapActivity extends FragmentActivity implements OnMapReadyCallback {
private static final int REQUEST_CHECK_SETTINGS = 0x1;
private static final int REQUEST_PERMISSIONS_REQUEST_CODE = 34;
private static final int REQUEST_FINE_LOCATION = 1;
private static final long UPDATE_INTERVAL_IN_MILLISECONDS = 1000;
private static final long FASTEST_INTERVAL = UPDATE_INTERVAL_IN_MILLISECONDS / 2;
private static final String TAG = "";
private static final long MIN_TIME_BW_UPDATES = 1;
private static final float MIN_DISTANCE_CHANGE_FOR_UPDATES = 1;
private boolean mRequestingLocationUpdates;
private GoogleMap mMap;
private GeoFire mGeoFire;
private LocationRequest locationRequest;
private LocationCallback locationCallback;
private Marker currentUser;
private DatabaseReference myLocationRef;
private GeoFire geoFire;
private List<LatLng> dangerousArea;
private LocationSettingsRequest mLocationSettingsRequest;
private SettingsClient mSettingsClient;
private FusedLocationProviderClient mFusedLocationClient;
private Button mStartUpdatesButton;
private Button mLogout;
private Button mRequest;
private TextView mLatitudeTextView;
private TextView mLongitudeTextView;
private TextView mLastUpdateTimeTextView;
private String mLatitudeLabel;
private String mLongitudeLabel;
private String mLastUpdateTimeLabel;
private String mLastUpdateTime;
private LocationCallback mLocationCallback;
private Location mCurrentLocation;
private LatLng mPickupLocationLatLng;
private LocationManager mLocationManager;
final CoPilotMapActivity mContext = this;
Location mLastLocation;
LocationRequest mLocationRequest;
Location location; // location
double latitude; // latitude
double longitude; // longitude
private LocationManager locationManager;
private double mLatitude;
private double Longitude;
private boolean isGPSEnabled;
private boolean isNetworkEnabled;
private boolean canGetLocation;
private Object markerDestination;
public CoPilotMapActivity() {
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_co_pilot_map);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
//Signout from firebase after declaring button up top
mLogout = (Button) findViewById(R.id.logout);
//Call an uber driver
mRequest = (Button) findViewById(R.id.request);
mLogout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(CoPilotMapActivity.this, "Sign out successful", Toast.LENGTH_SHORT).show();
FirebaseAuth.getInstance().signOut();
//To take you to a different page you create an intent
Intent intent = new Intent(CoPilotMapActivity.this, MainActivity.class);
startActivity(intent);
finish();
return;
}
});
//ACCESS USER'S LOCATION.................................
Dexter.withActivity(this)
.withPermission(Manifest.permission.ACCESS_FINE_LOCATION)
.withListener(new PermissionListener() {
@Override
public void onPermissionGranted(PermissionGrantedResponse response) {
//Obtain the SupportMapFragment and get notified when map is ready to be used
buildLocationRequest();
buildLocationCallback();
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(CoPilotMapActivity.this);
SupportMapFragment mapFragment = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(CoPilotMapActivity.this);
}
@Override
public void onPermissionDenied(PermissionDeniedResponse response) {
Toast.makeText(CoPilotMapActivity.this,"You must enable permission", Toast.LENGTH_SHORT).show();
}
@Override
public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token) {
}
}).check();
//requesting a driver
//WORK ON THIS PART NULL POINTER EXCEPTION COMING UP ON GETLATITUDE FUNCTION
mRequest.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(location!= null){
double latitude = location.getLatitude();
double longitude = location.getLongitude();
}
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
String userId = FirebaseAuth.getInstance().getCurrentUser().getUid();
//send request and pinpoint exact location from where customer
//will be picked up from
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("customerRequest");
GeoFire geoFire = new GeoFire(ref);
geoFire.setLocation(userId, new GeoLocation(mLastLocation.getLatitude(),mLastLocation.getLongitude()),
new GeoFire.CompletionListener() {
@Override
public void onComplete(String key, DatabaseError error) {
if(location!= null){
double latitude = location.getLatitude();
double longitude = location.getLongitude();
}
if (error != null){
System.err.println("There was an error saving the location to GeoFire: " + error);
}else {
System.out.println("Location saved on server successfully!");
}
}
});
geoFire.getLocation(userId, new com.firebase.geofire.LocationCallback() {
@Override
public void onLocationResult(String key, GeoLocation location) {
if (location != null) {
System.out.println(String.format("The location for key %s is [%f,%f]", key, location.latitude,
location.longitude));
}else {
System.out.println(String.format("There is no location for key %s in GeoFire", key));
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
//THIS STILL ISN'T BLOODY WORKING RETRIEVING DRIVERS LOCATION WHEN BUTTON IS CALLED SO
//WHAT TO DO DAMMIT
//create marker for customers pickup spot
mPickupLocationLatLng = new LatLng(mLastLocation.getLatitude(),mLastLocation.getLongitude());
//change text of request button when it is pressed to request driver
mRequest.setText("Getting your driver...");
}
});
}
LOGCAT
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.e.friendrides, PID: 18776
java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference
at com.e.friendrides.CoPilotMapActivity$3.onClick(CoPilotMapActivity.java:214)
at android.view.View.performClick(View.java:6663)
at android.view.View.performClickInternal(View.java:6635)
at android.view.View.access$3100(View.java:794)
at android.view.View$PerformClick.run(View.java:26199)
at android.os.Handler.handleCallback(Handler.java:907)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:216)
at android.app.ActivityThread.main(ActivityThread.java:7625)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:987)