I’m currently working on an Android App and, almost every time I use it, I get a an error. Most of the time it doesn’t crash the app, but it is still frustrating that I’m seeing this error. I thought I did a check for it, but I could be wrong. Thanks for the help! The relevant code is below. (It’s relevant because the line outside the if statement is throwing the NullPointerException.)
Activity activity;
if(activity == null)
{
activity = new Activity();
}
Intent intent = new Intent(activity, Service.class);
You should post some more of the surrounding code, but your problem is that creating new
Intentrequires a validContext. Usually you create anIntentwithin anActivity(orServiceorBroadcastReceiver) class so you can just do something like:Occasionally you’ll create it somewhere else and pass it that valid
Context, but you should pretty much never create anActivityby calling the constructor directly. There’s a lot of other initialization necessary to make it useful.