Reputation: 177
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);
Upvotes: 0
Views: 344
Reputation: 947
As postet previously there is more to initiate for an activity than calling the constructor. Probably you get a null pointer exception deep within the Intent Constructer where it is trying to get some of the Activityinformation usually provided.
If you really want to create a Service, heres a link for starting a Service, but you should really read the whole article and probably some more of the activity lifecycle ressources.
http://developer.android.com/guide/topics/fundamentals/services.html#StartingAService
Upvotes: 0
Reputation: 36302
You should post some more of the surrounding code, but your problem is that creating new Intent
requires a valid Context
. Usually you create an Intent
within an Activity
(or Service
or BroadcastReceiver
) class so you can just do something like:
Intent intent = new Intent(this, Service.class);
Occasionally you'll create it somewhere else and pass it that valid Context
, but you should pretty much never create an Activity
by calling the constructor directly. There's a lot of other initialization necessary to make it useful.
Upvotes: 0
Reputation: 17206
You don't usually instantiate the Activity class in this manner. Please see the documentation on the Android Activity class here:
http://developer.android.com/reference/android/app/Activity.html
Upvotes: 3