I have a line in an Android app which reads as follows:
Intent intent = new Intent(this,MyView.class);
Unfortunately, it appears that on occasions this crashes, however I haven't been able to reproduce the crash, possibly because I don't understand in what circumstances this would fail. The crash is a java.lang.NullPointerException
as you may have already guessed.
From reading other solutions, I see that I can replace this
with getApplicationContext()
, but that still doesn't help as I want to understand:
- In what circumstances this might happen
- Why
this
doesn't work correctly
I am of course assuming this
is the problem - I'm assuming that MyView.class
would never be null, which I think is correct?
For completeness, I should explain that this is written within a callback. Here is the complete code for the function:
@Override
public void didReceiveLoginResponse(boolean status) {
if(status) {
Intent intent = new Intent(this,MyView.class);
startActivity(intent);
}
}
Many thanks for any helpful ideas!
Edit: To be clear, I am not asking what a nullPointerException is. I am asking in what circumstances would this line contain a nullPointerException. If the view no longer exists, how can the function even run (surely the null bit would be the view/function, not a specific line within it?)