Решено:"Проверьте FirebaseAuth.getInstance (). GetCurrentUser ()! = Null перед вызовом getUid."- Srikar Reddy (в комментариях)
Контекст: мое приложение использует Firebase и Geofire, чтобы получить местоположение пользователя и обновить его.Когда пользователь не на экране карты, он удаляет свое местоположение Geofire из базы данных Firebase.Это приложение для отслеживания в реальном времени.Приложение правильно отслеживает и обновляет пользователя.Все отлично работаетИх данные Geofire удаляются из Firebase правильно.Кроме того, когда я выхожу из системы, я сталкиваюсь с проблемами.Вход в систему работает тоже отлично.
Проблема: при выходе из системы приложение вылетает с этой ошибкой:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a null object reference
Что я пробовал:
String vendorId = Objects.requireNonNull(FirebaseAuth.getInstance().getCurrentUser()).getUid();
Но также вылетает с этой ошибкой:
java.lang.RuntimeException: Unable to stop activity {com.example.zzyzj.eloteroman/com.example.zzyzj.eloteroman.VendorMapsActivity}: java.lang.NullPointerException
Мой код:
//Logout Menu Option Button
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// If Logout Button is clicked within 2 Seconds log user out
case R.id.logoutMenuOption:
if (logoutAppPressAgain + 2000 > System.currentTimeMillis()) {
logoutToast.cancel();
// Remove VendorOnline Child before logging out to prevent crash
removeVendorOnline();
FirebaseAuth.getInstance().signOut();
Intent logoutIntent = new Intent(VendorMapsActivity.this, WelcomeActivity.class);
startActivity(logoutIntent);
finish();
} else {
logoutToast = Toast.makeText(getBaseContext(), R.string.press_button_again_to_logout, Toast.LENGTH_SHORT);
logoutToast.show();
}
logoutAppPressAgain = System.currentTimeMillis();
}
return super.onOptionsItemSelected(item);
}
@Override
public void onLocationChanged(Location location) {
lastLocation = location;
if (currentUserLocationMarker != null) {
currentUserLocationMarker.remove();
}
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title(getString(R.string.user_current_location_marker_title));
markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.corn_icon));
currentUserLocationMarker = mMap.addMarker(markerOptions);
float zoom = 17.0f;
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom));
mMap.getUiSettings().setRotateGesturesEnabled(false);
mMap.getUiSettings().setZoomControlsEnabled(false);
// Adds VendorOnline Child to Firebase when Vendor is On This Activity
addVendorOnline();
}
@Override
protected void onStart() {
super.onStart();
if (googleApiClient != null) {
googleApiClient.connect();
}
}
@Override
protected void onStop() {
super.onStop();
// When Vendor is not on this screen activity it will remove their data from Firebase
removeVendorOnline();
if (googleApiClient.isConnected()) {
googleApiClient.disconnect();
}
}
// When user swipe closes app it logs them out
@Override
protected void onDestroy() {
super.onDestroy();
removeVendorOnline();
FirebaseAuth.getInstance().signOut();
}
// Prevent user from going to unwanted Activities when back button is pressed, instead user logout
@Override
public void onBackPressed() {
if (exitAppPressBack + 2000 > System.currentTimeMillis()) {
exitAppBackToast.cancel();
super.onBackPressed();
// Remove VendorOnline Child before logging out to prevent crash
removeVendorOnline();
FirebaseAuth.getInstance().signOut();
Intent logoutIntent = new Intent(VendorMapsActivity.this, WelcomeActivity.class);
startActivity(logoutIntent);
finish();
} else {
exitAppBackToast = Toast.makeText(getBaseContext(), R.string.press_back_one_more_time_to_exit, Toast.LENGTH_SHORT);
exitAppBackToast.show();
}
exitAppPressBack = System.currentTimeMillis();
}
// Code to store Vendor data when a Vendor is Online in Firebase
// Creates new Child within Firebase Database "VendorsOnline" when a Vendor is Online
// Uses Geofire to update location and update Vendor Online Data in Firebase
public void addVendorOnline(){
String vendorId = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference vendorIdReference = FirebaseDatabase.getInstance().getReference("VendorOnline");
GeoFire vendorGeoFire = new GeoFire(vendorIdReference);
vendorGeoFire.setLocation(vendorId, new GeoLocation(lastLocation.getLatitude(), lastLocation.getLongitude()));
}
// Removes Vendor from VendorOnline Child in Firebase
public void removeVendorOnline() {
String vendorId = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference vendorIdReference = FirebaseDatabase.getInstance().getReference("VendorOnline");
GeoFire vendorGeoFire = new GeoFire(vendorIdReference);
vendorGeoFire.removeLocation(vendorId);
}