java.lang.RuntimeException unable to instantiate service: java.lang.NullPointerException

13,518

Solution 1

You cannot call getSystemService() from an initializer (as you originally were) or from the constructor (as you are now). Please override onCreate(), and call getSystemService() there.

Basically, until onCreate() is called (or, more accurately, until after you call super.onCreate() from your onCreate()), the inherited methods on Service are not yet ready for your use.

Solution 2

I had the same error. My mistake was that the Service didnt have an empty default constructor. Here's the code that solved it:

public class MyService extends IntentService {

    public MyService() { 
         super(null); // That was the lacking constructor
    }

    public MyService(String name) {
        super(name);
    }

    //...

}
Share:
13,518
Mitodina
Author by

Mitodina

Updated on June 13, 2022

Comments

  • Mitodina
    Mitodina almost 2 years

    I was trying to create an activity that start a service (in a new thread). It consists in a layout with two editText and a button called Send. The point is that when I execute the MainActivity, it throws that:

    06-15 22:32:13.312: E/AndroidRuntime(643): FATAL EXCEPTION: main
    06-15 22:32:13.312: E/AndroidRuntime(643): java.lang.RuntimeException: Unable to instantiate service hikoki.services.NotificationsService: java.lang.NullPointerException
    06-15 22:32:13.312: E/AndroidRuntime(643):  at android.app.ActivityThread.handleCreateService(ActivityThread.java:2237)
    06-15 22:32:13.312: E/AndroidRuntime(643):  at android.app.ActivityThread.access$1600(ActivityThread.java:123)
    06-15 22:32:13.312: E/AndroidRuntime(643):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1201)
    06-15 22:32:13.312: E/AndroidRuntime(643):  at android.os.Handler.dispatchMessage(Handler.java:99)
    06-15 22:32:13.312: E/AndroidRuntime(643):  at android.os.Looper.loop(Looper.java:137)
    06-15 22:32:13.312: E/AndroidRuntime(643):  at android.app.ActivityThread.main(ActivityThread.java:4424)
    06-15 22:32:13.312: E/AndroidRuntime(643):  at java.lang.reflect.Method.invokeNative(Native Method)
    06-15 22:32:13.312: E/AndroidRuntime(643):  at java.lang.reflect.Method.invoke(Method.java:511)
    06-15 22:32:13.312: E/AndroidRuntime(643):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
    06-15 22:32:13.312: E/AndroidRuntime(643):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
    06-15 22:32:13.312: E/AndroidRuntime(643):  at dalvik.system.NativeStart.main(Native Method)
    06-15 22:32:13.312: E/AndroidRuntime(643): Caused by: java.lang.NullPointerException
    06-15 22:32:13.312: E/AndroidRuntime(643):  at android.content.ContextWrapper.getSystemService(ContextWrapper.java:386)
    06-15 22:32:13.312: E/AndroidRuntime(643):  at hikoki.services.NotificationsService.<init>(NotificationsService.java:35)
    06-15 22:32:13.312: E/AndroidRuntime(643):  at java.lang.Class.newInstanceImpl(Native Method)
    06-15 22:32:13.312: E/AndroidRuntime(643):  at java.lang.Class.newInstance(Class.java:1319)
    06-15 22:32:13.312: E/AndroidRuntime(643):  at android.app.ActivityThread.handleCreateService(ActivityThread.java:2234)
    06-15 22:32:13.312: E/AndroidRuntime(643):  ... 10 more
    

    The code of Main Activity is this:

    public class MainActivity extends Activity {
        private String TAG = getClass().getSimpleName();
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            Thread t= new Thread(){
                public void run(){
                    Intent intent=new Intent(getContext(),NotificationsService.class);
                    //Intent intent=new Intent("hikoki.services.NotificationsService");
                    Log.d(TAG,"sending notificationsService");
                    startService(intent);
                }
            };
            t.start();
        }
    
        protected Context getContext() {    
            return this;
        }
    }
    

    An the code od NotificationsService is here:

    public class NotificationsService extends IntentService{
        private static  int TIME_INTERVAL_MILIS=5000;
        private static final int REFRESH=10;
        private  NotificationManager noteManager;
        private static List<FlightStatusNote> flights= new ArrayList<FlightStatusNote>();
    
        public NotificationsService(){
            super("NotificationsService"); 
            noteManager= NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE)
        }
    }
    

    and the AndroidManifest is this:

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="hikoki.services"
        android:versionCode="1"
        android:versionName="1.0" >
    
    <uses-sdk
        android:minSdkVersion="15"
        android:targetSdkVersion="17" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="hikoki.services.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
    
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name=".FlightStatusService"></service>
        <service android:enabled="true" android:name=".NotificationsService"></service>
    </application>
    
    </manifest>
    
    • njzk2
      njzk2 almost 11 years
      you cannot call getSystemService before onStart is called because your context is not initialized.
    • Mitodina
      Mitodina almost 11 years
      @njzk2 thanks for that! I changed it, but it is still not working :/
    • CommonsWare
      CommonsWare almost 11 years
      Please post the new stack trace, as you are crashing somewhere else now.
    • Mitodina
      Mitodina almost 11 years
      @CommonsWare I edited the post with the new stack trace.
    • G. Blake Meike
      G. Blake Meike almost 11 years
      I know this is slightly off topic, but what are you trying to accomplish, here? The service that you start will not run on the newly created thread...
    • Mitodina
      Mitodina almost 11 years
      @G.BlakeMeike good question! I'm trying to create a thread that runs in background (it requests to a server for every five minutes, for example. It causes "code pollution" I know, but i din't find a better way). It's strange what you're saying, because I run the program and it's seems to works ok (the thread sleeps, and the "unresponsive aplication" message didn't appeared :S). Please, tell me why are you telling that (because I got confused :S)
    • G. Blake Meike
      G. Blake Meike almost 11 years
      Sort of what I guessed. If that service is part of your application then, no matter what thread you run startService from, it will run on the main/UI thread. You will still, eventually, get those ANRs. Have a look at using service that starts a thread and initializes it as a Looper. Then use Handler.postDelayed. A second problem probably, is that your application (process) will be killed eventually. If you are trying to poll continuously, have a look at the AlarmManager and an IntentService.
  • DIRTY DAVE
    DIRTY DAVE over 4 years
    This fixed my issue!