I have Google Map Activity that launches after a user logs in using Back4App Parse server. In the onCreate method of this activity, I can print the username to LogCat with a call to ParseUser.getCurrentUser().getUsername(). I can print it again in the onMapReady method with the same call. However, when I go to log the user out after clicking the logout button, ParseUser.getCurrentUser().getUsername() returns null and crashes my app. I know I can store the username in a String when the call does work, but I want to know WHY the user is inaccessible in my onClick method.
public class PassengerMapActivity extends FragmentActivity implements OnMapReadyCallback,
View.OnClickListener {
private GoogleMap map;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_passenger_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);
Log.i("onCreate", ParseUser.getCurrentUser().getUsername()); // this works
}
@Override
public void onMapReady(GoogleMap googleMap) {
map = googleMap;
Log.i("onMapReady", ParseUser.getCurrentUser().getUsername()); // this works too
locationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
updateMapCamera(location);
}
... // unused interface methods
};
}
@Override
public void onClick(View view) {
switch(view.getId()) {
case R.id.btn_logout_passenger:
final String currentUser = ParseUser.getCurrentUser().getUsername(); // this returns null
ParseUser.logOutInBackground(new LogOutCallback() {
@Override
public void done(ParseException e) {
if(e == null) {
Toast.makeText(PassengerMapActivity.this,
currentUser + " has logged out", Toast.LENGTH_SHORT).show();
}
}
});
break;
Log Info: 2020-03-22 17:11:47.035 2969-2969/packageName E/AndroidRuntime: FATAL EXCEPTION: main Process: packageName, PID: 2969 java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.parse.ParseUser.getUsername()' on a null object reference