Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NullPointerException in Service's constructor

In my Android project, I have a Service :

public class MyService extends Service{

    //I defined a explicite contructor 
    public MyService(){
       //NullPointerException here, why?
       File dir = getDir("my_dir", Context.MODE_PRIVATE);
    }

    @Override
    public void onCreate(){
      super.onCreate();
      ...
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
    super.onStartCommand(intent, flags, startId);
        ...
    }

}

I know normally, I shouldn't explicitly define a constructor for Android Service. But in my case, I want to use the constructor to create a directory in my internal storage.

When I try it, I got NullPointerException, which I don't understand why? Could anyone explain to me the reason why I got NullPoineterException when call getDir(...) in my explicite constructor ?

like image 750
Leem.fin Avatar asked Jan 11 '23 11:01

Leem.fin


2 Answers

getDir() is a method in Context.

The service is not set up to be used as a Context until onCreate().

Basically, the framework sets up services (and activities for that matter) the following way:

  1. Create the object
  2. Set up the Context, with appropriate resources for the current configuration
  3. Call onCreate() on the object

You cannot do anything that requires the object to be a properly set up Context at step 1 i.e. during member variable initialization or constructor.

like image 190
laalto Avatar answered Jan 18 '23 23:01

laalto


You have to use service lifecycle function onCreate(). onCreate function run only once in a service lifecycle and works as constructor. If you want it to update anywhere then you can put it in onStartCommand(Intent intent, int flags, int startId).

like image 20
vaibhav kumar Avatar answered Jan 18 '23 22:01

vaibhav kumar