NullPointerException in service constructor

In my Android project, I have 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 fine, I should not explicitly define the 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, I got a NullPointerException that I don’t understand why? Can someone explain to me the reason I got a NullPoineterException when called getDir(...)in my explicite constructor?

+4
source share
4 answers

getDir()- this is method c Context.

Context onCreate().

, ( , ) :

  • Context
  • onCreate()

, , Context 1, .

+6

onCreate(). onCreate . , , onStartCommand (Intent intent, int flags, int startId).

+1

, - , getDir Context . :

http://androidxref.com/4.4.2_r1/xref/frameworks/base/core/java/android/content/ContextWrapper.java#244

243    @Override
244    public File getDir(String name, int mode) {
245        return mBase.getDir(name, mode);
246    }

, mBase null, NPE

mBase :

56    public ContextWrapper(Context base) {
57        mBase = base;
58    }

ContextWrapper, :

http://androidxref.com/4.4.2_r1/xref/frameworks/base/core/java/android/app/Service.java#294

294    public Service() {
295        super(null);
296    }

Service.onCreate() ( ) - , , aplication.

+1

As @laalto said. The service is not configured to be used as a context until it is created. () ..

So, create one global variable Context .

Context ctx;

Also create a constructor for the MyService class .

public MyService(Context mContext){

   this.ctx = mContext;
   File dir = ctx.getDir("my_dir", Context.MODE_PRIVATE);
}
+1
source

All Articles